Skip to content

Instantly share code, notes, and snippets.

@rccc
Last active January 26, 2017 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rccc/0c3d3e05f092de66e39bc91c9af82dc7 to your computer and use it in GitHub Desktop.
Save rccc/0c3d3e05f092de66e39bc91c9af82dc7 to your computer and use it in GitHub Desktop.

1. Créer le formulaire

Il faut créer un fichier nommé 'searchform-advanced.php.php' et l'intégrer avec : get_template_part( 'advanced', 'searchform' );.

<form method="get" id="advanced-searchform" role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>">

    <h3><?php _e( 'Advanced Search', 'textdomain' ); ?></h3>

    <!-- PASSING THIS TO TRIGGER THE ADVANCED SEARCH RESULT PAGE FROM functions.php -->
    <input type="hidden" name="search" value="advanced">

    <label for="s" class=""><?php _e( 'Name: ', 'textdomain' ); ?></label><br>
    <input type="text" value="" placeholder="<?php _e( 'Type the Car Name', 'textdomain' ); ?>" name="s" id="name" />

    <label for="model" class=""><?php _e( 'Select a Model: ', 'textdomain' ); ?></label><br>
    <select name="model" id="model">
        <option value=""><?php _e( 'Select one...', 'textdomain' ); ?></option>
        <option value="model1"><?php _e( 'Model 1', 'textdomain' ); ?></option>
        <option value="model2"><?php _e( 'Model 2', 'textdomain' ); ?></option>
    </select>

    <input type="submit" id="searchsubmit" value="Search" />

</form>

2. Modifier la requête de recherche

Dans le fichier funcitons.php, ajouter le code suivant, qu'il faudra adapter

add_action( 'pre_get_posts', 'advanced_search_query' );
function advanced_search_query( $query ) {

    if ( isset( $_REQUEST['search'] ) && $_REQUEST['search'] == 'advanced' && ! is_admin() && $query->is_search && $query->is_main_query() ) {

        $_model = $_GET['model'] != '' ? $_GET['model'] : '';

        $meta_query = array(
                            array(
                                'key'     => '', // assumed your meta_key is 'car_model'
                                'value'   => $_model,
                                'compare' => 'LIKE',
                            )
                        )
        );
        $query->set( 'meta_query', $meta_query );

    }
}

3. Créer un template pour les résultats de la recherche

Créer un fichier nommé advanced-search-template.php et ajouter le code suivant dans le fichier functions.php :

add_action('template_include', 'advanced_search_template');
function advanced_search_tmpl( $template ) {
  if ( isset( $_REQUEST['search'] ) && $_REQUEST['search'] == 'advanced' && is_search() ) {
     $t = locate_template('advanced-search-template.php');
     if ( ! empty($t) ) {
         $template = $t;
     }
  }
  return $template;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment