Aggiungere un menu a discesa Categoria al Modulo di Ricerca
Uno dei modi più popolari per integrare la ricerca è consentire ai visitatori di controllare autonomamente il pool di risultati. Questo di solito si presenta sotto forma di consentire loro di scegliere una categoria specifica da un menu a discesa (casella di selezione) da associare alla loro ricerca.
Questo articolo spiegherà come puoi realizzare tre diversi approcci per aggiungere un menu a discesa delle categorie al tuo modulo di ricerca.
- Crea il tuo modulo di ricerca con un menu a discesa delle categorie
- Personalizza l'estensione Shortcodes per includere un menu a discesa delle categorie
- Personalizza il modulo di ricerca predefinito per includere un menu a discesa per la selezione delle categorie
Creazione del tuo modulo di ricerca
La creazione del tuo modulo di ricerca implica la modifica dei file del tuo tema per includere i campi di input e i pulsanti che vogliamo includere. A un livello più basilare, puoi aggiungere quanto segue al file del template del tuo tema dove desideri che appaia il modulo:
| <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> | |
| <label> | |
| <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span> | |
| <input type="search" class="search-field" placeholder="Search..." value="<?php echo esc_attr( get_search_query() ); ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ); ?>" /> | |
| </label> | |
| <?php | |
| // output all of our Categories | |
| // for more information see http://codex.wordpress.org/Function_Reference/wp_dropdown_categories | |
| $swp_cat_dropdown_args = array( | |
| 'show_option_all' => __( 'Any Category' ), | |
| 'name' => 'swp_category_limiter', | |
| ); | |
| wp_dropdown_categories( $swp_cat_dropdown_args ); | |
| ?> | |
| <input type="submit" class="search-submit" value="Search" /> | |
| </form> |
Basato sul modulo di ricerca predefinito fornito da WordPress, questo modulo genera un campo per la query di ricerca, una casella di selezione contenente tutte le tue categorie e un pulsante per attivare la ricerca. Nota gli argomenti passati a wp_dropdown_categories() che definiscono l'etichetta 'Qualsiasi categoria' e impostano il name del menu a discesa come swp_category_limiter.
Con il tuo modulo al suo posto, l'ultimo passo è dire a SearchWP di prendere in considerazione il valore del menu a discesa inviato durante l'esecuzione delle ricerche. Per fare ciò useremo un Mod. Useremo l'ID della categoria inviato nel menu a discesa per limitare il nostro pool di risultati di ricerca alla categoria scelta.
Nota: nota che la variabile che stiamo cercando era quella che abbiamo usato per impostare il name della select che è stata generata da wp_dropdown_categories()
All hooks should be added to your custom SearchWP Customizations Plugin.
| <?php | |
| // Limit SearchWP results to chosen Category from dropdown. | |
| // @link https://searchwp.com/documentation/knowledge-base/category-select-dropdown/ | |
| add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
| global $wpdb; | |
| // Only proceed if a Category was chosen from the dropdown. | |
| if ( ! isset( $_GET['swp_category_limiter'] ) || empty( intval( $_GET['swp_category_limiter'] ) ) ) { | |
| return $mods; | |
| } | |
| // Optional: only proceed if we're using a specific Engine. | |
| // if ( 'default' !== $query->get_engine()->get_name() ) { | |
| // return $mods; | |
| // } | |
| $alias = 'swpkbcat'; | |
| $tax_query = new WP_Tax_Query( [ [ | |
| 'taxonomy' => 'category', | |
| 'field' => 'term_id', | |
| 'terms' => absint( $_GET['swp_category_limiter'] ), | |
| ] ] ); | |
| $tq_sql = $tax_query->get_sql( $alias, 'ID' ); | |
| $mod = new \SearchWP\Mod(); | |
| // If the JOIN is empty, WP_Tax_Query assumes we have a JOIN with wp_posts, so let's make that. | |
| if ( ! empty( $tq_sql['join'] ) ) { | |
| // Queue the assumed wp_posts JOIN using our alias. | |
| $mod->raw_join_sql( function( $runtime ) use ( $wpdb, $alias ) { | |
| return "LEFT JOIN {$wpdb->posts} {$alias} ON {$alias}.ID = {$runtime->get_foreign_alias()}.id"; | |
| } ); | |
| // Queue the WP_Tax_Query JOIN which already has our alias. | |
| $mod->raw_join_sql( $tq_sql['join'] ); | |
| // Queue the WP_Tax_Query WHERE which already has our alias. | |
| $mod->raw_where_sql( '1=1 ' . $tq_sql['where'] ); | |
| } else { | |
| // There's no JOIN here because WP_Tax_Query assumes a JOIN with wp_posts already | |
| // exists. We need to rebuild the tax_query SQL to use a functioning alias. The Mod | |
| // will ensure the JOIN, and we can use that Mod's alias to rebuild our tax_query. | |
| $mod->set_local_table( $wpdb->posts ); | |
| $mod->on( 'ID', [ 'column' => 'id' ] ); | |
| $mod->raw_where_sql( function( $runtime ) use ( $tax_query ) { | |
| $tq_sql = $tax_query->get_sql( $runtime->get_local_table_alias(), 'ID' ); | |
| return '1=1 ' . $tq_sql['where']; | |
| } ); | |
| } | |
| $mods[] = $mod; | |
| return $mods; | |
| }, 20, 2 ); |
Questo snippet verifica che sia stato scelto un valore non vuoto dal menu a discesa. In tal caso, il nostro Mod viene creato e aggiunto alla Query.
Utilizza l'estensione Shortcodes di SearchWP
L'estensione Shortcodes di SearchWP ti consente di generare facilmente moduli di ricerca e controllare le pagine dei risultati di ricerca utilizzando gli Shortcodes di WordPress. Ecco un esempio di modulo di ricerca che include un menu a discesa Categorie tra cui scegliere:
All hooks should be added to your custom SearchWP Customizations Plugin.
| <?php | |
| // UNCOMMENT THIS IF YOU WANT TO USE SHORTCODES IN WIDGETS | |
| // add_filter( 'widget_text', 'do_shortcode' ); | |
| // output the categories dropdown | |
| function my_searchwp_shortcodes_inject_categories() { | |
| echo '<p class="searchwp-shortcodes-categories">'; | |
| // for more information see http://codex.wordpress.org/Function_Reference/wp_dropdown_categories | |
| $swp_cat_dropdown_args = array( | |
| 'show_option_all' => __( 'Any Category' ), | |
| 'name' => 'swp_category_limiter', | |
| ); | |
| wp_dropdown_categories( $swp_cat_dropdown_args ); | |
| echo '</p>'; | |
| } | |
| add_action( 'searchwp_shortcodes_after_input', 'my_searchwp_shortcodes_inject_categories' ); |
Questo si occupa del nostro modulo di ricerca, includerà automaticamente un menu a discesa delle nostre categorie tra il campo di ricerca e il pulsante di invio. Nota che in questo snippet abbiamo personalizzato il name del menu a discesa in swp_category_limiter, che useremo successivamente.
Finora abbiamo solo impostato il modulo per generare un menu a discesa che consentirà al visitatore di definire una categoria per la restrizione dei risultati, dobbiamo ancora acquisire tali informazioni quando il modulo viene inviato e informare SearchWP al riguardo.
Per fare ciò useremo un Mod. Useremo l'ID della categoria inviato nel menu a discesa per limitare il nostro pool di risultati di ricerca alla categoria scelta.
Nota: nota che la variabile che stiamo cercando era quella che abbiamo usato per impostare il name della select che è stata generata da wp_dropdown_categories()
All hooks should be added to your custom SearchWP Customizations Plugin.
| <?php | |
| // Limit SearchWP results to chosen Category from dropdown. | |
| // @link https://searchwp.com/documentation/knowledge-base/category-select-dropdown/ | |
| add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
| global $wpdb; | |
| // Only proceed if a Category was chosen from the dropdown. | |
| if ( ! isset( $_GET['swp_category_limiter'] ) || empty( intval( $_GET['swp_category_limiter'] ) ) ) { | |
| return $mods; | |
| } | |
| // Optional: only proceed if we're using a specific Engine. | |
| // if ( 'default' !== $query->get_engine()->get_name() ) { | |
| // return $mods; | |
| // } | |
| $alias = 'swpkbcat'; | |
| $tax_query = new WP_Tax_Query( [ [ | |
| 'taxonomy' => 'category', | |
| 'field' => 'term_id', | |
| 'terms' => absint( $_GET['swp_category_limiter'] ), | |
| ] ] ); | |
| $tq_sql = $tax_query->get_sql( $alias, 'ID' ); | |
| $mod = new \SearchWP\Mod(); | |
| // If the JOIN is empty, WP_Tax_Query assumes we have a JOIN with wp_posts, so let's make that. | |
| if ( ! empty( $tq_sql['join'] ) ) { | |
| // Queue the assumed wp_posts JOIN using our alias. | |
| $mod->raw_join_sql( function( $runtime ) use ( $wpdb, $alias ) { | |
| return "LEFT JOIN {$wpdb->posts} {$alias} ON {$alias}.ID = {$runtime->get_foreign_alias()}.id"; | |
| } ); | |
| // Queue the WP_Tax_Query JOIN which already has our alias. | |
| $mod->raw_join_sql( $tq_sql['join'] ); | |
| // Queue the WP_Tax_Query WHERE which already has our alias. | |
| $mod->raw_where_sql( '1=1 ' . $tq_sql['where'] ); | |
| } else { | |
| // There's no JOIN here because WP_Tax_Query assumes a JOIN with wp_posts already | |
| // exists. We need to rebuild the tax_query SQL to use a functioning alias. The Mod | |
| // will ensure the JOIN, and we can use that Mod's alias to rebuild our tax_query. | |
| $mod->set_local_table( $wpdb->posts ); | |
| $mod->on( 'ID', [ 'column' => 'id' ] ); | |
| $mod->raw_where_sql( function( $runtime ) use ( $tax_query ) { | |
| $tq_sql = $tax_query->get_sql( $runtime->get_local_table_alias(), 'ID' ); | |
| return '1=1 ' . $tq_sql['where']; | |
| } ); | |
| } | |
| $mods[] = $mod; | |
| return $mods; | |
| }, 20, 2 ); |
Questo snippet verifica che sia stato scelto un valore non vuoto dal menu a discesa. In tal caso, il nostro Mod viene creato e aggiunto alla Query.
Modifica il modulo di ricerca predefinito per includere un menu a discesa delle categorie
WordPress ci consente di filtrare il modulo di ricerca predefinito presente in molti temi. Viene generato da una chiamata a get_search_form() che può essere completamente personalizzata includendo un file denominato searchform.php nella directory del tuo tema, o tramite il filtro get_search_form. Per questo esempio utilizzeremo il filtro get_search_form. Per utilizzare questo filtro lavorerai nel file functions.php del tuo tema.
Per includere un menu a discesa delle categorie nel modulo di ricerca predefinito del tuo sito, usa il seguente snippet:
All hooks should be added to your custom SearchWP Customizations Plugin.
| <?php | |
| // adds a Categories dropdown to the search form | |
| function my_searchwp_get_search_form_with_categories_dropdown( $form ) { | |
| ob_start(); ?> | |
| <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> | |
| <label> | |
| <span class="screen-reader-text">Search For</span> | |
| <input type="search" class="search-field" placeholder="Search..." value="<?php echo esc_attr( get_search_query() ); ?>" name="s" title="Search for:" /> | |
| </label> | |
| <?php | |
| // for more information see http://codex.wordpress.org/Function_Reference/wp_dropdown_categories | |
| $swp_cat_dropdown_args = array( | |
| 'show_option_all' => __( 'Any Category' ), | |
| 'name' => 'swp_category_limiter', | |
| ); | |
| wp_dropdown_categories( $swp_cat_dropdown_args ); | |
| ?> | |
| <input type="submit" class="search-submit" value="Search" /> | |
| </form> | |
| <?php return ob_get_clean(); | |
| } | |
| add_filter( 'get_search_form', 'my_searchwp_get_search_form_with_categories_dropdown' ); |
Il codice del modulo utilizzato qui si basa sul modulo di ricerca predefinito fornito con WordPress. C'è la possibilità che il tuo tema abbia precedentemente personalizzato il modulo e tu voglia semplicemente aggiungere il menu a discesa. Puoi semplicemente modificare il codice del modulo per farlo corrispondere a quello fornito con il tuo tema e aggiungere le righe 11-18 da quel campione di codice dove vuoi che appaia il tuo menu a discesa delle Categorie.
Questo snippet modifica solo il modulo di ricerca, dobbiamo ancora acquisire il valore dal menu a discesa e dire a SearchWP di limitare i risultati a una Categoria specifica.
Per fare ciò useremo un Mod. Useremo l'ID della categoria inviato nel menu a discesa per limitare il nostro pool di risultati di ricerca alla categoria scelta.
Nota: nota che la variabile che stiamo cercando era quella che abbiamo usato per impostare il name della select che è stata generata da wp_dropdown_categories()
All hooks should be added to your custom SearchWP Customizations Plugin.
| <?php | |
| // Limit SearchWP results to chosen Category from dropdown. | |
| // @link https://searchwp.com/documentation/knowledge-base/category-select-dropdown/ | |
| add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
| global $wpdb; | |
| // Only proceed if a Category was chosen from the dropdown. | |
| if ( ! isset( $_GET['swp_category_limiter'] ) || empty( intval( $_GET['swp_category_limiter'] ) ) ) { | |
| return $mods; | |
| } | |
| // Optional: only proceed if we're using a specific Engine. | |
| // if ( 'default' !== $query->get_engine()->get_name() ) { | |
| // return $mods; | |
| // } | |
| $alias = 'swpkbcat'; | |
| $tax_query = new WP_Tax_Query( [ [ | |
| 'taxonomy' => 'category', | |
| 'field' => 'term_id', | |
| 'terms' => absint( $_GET['swp_category_limiter'] ), | |
| ] ] ); | |
| $tq_sql = $tax_query->get_sql( $alias, 'ID' ); | |
| $mod = new \SearchWP\Mod(); | |
| // If the JOIN is empty, WP_Tax_Query assumes we have a JOIN with wp_posts, so let's make that. | |
| if ( ! empty( $tq_sql['join'] ) ) { | |
| // Queue the assumed wp_posts JOIN using our alias. | |
| $mod->raw_join_sql( function( $runtime ) use ( $wpdb, $alias ) { | |
| return "LEFT JOIN {$wpdb->posts} {$alias} ON {$alias}.ID = {$runtime->get_foreign_alias()}.id"; | |
| } ); | |
| // Queue the WP_Tax_Query JOIN which already has our alias. | |
| $mod->raw_join_sql( $tq_sql['join'] ); | |
| // Queue the WP_Tax_Query WHERE which already has our alias. | |
| $mod->raw_where_sql( '1=1 ' . $tq_sql['where'] ); | |
| } else { | |
| // There's no JOIN here because WP_Tax_Query assumes a JOIN with wp_posts already | |
| // exists. We need to rebuild the tax_query SQL to use a functioning alias. The Mod | |
| // will ensure the JOIN, and we can use that Mod's alias to rebuild our tax_query. | |
| $mod->set_local_table( $wpdb->posts ); | |
| $mod->on( 'ID', [ 'column' => 'id' ] ); | |
| $mod->raw_where_sql( function( $runtime ) use ( $tax_query ) { | |
| $tq_sql = $tax_query->get_sql( $runtime->get_local_table_alias(), 'ID' ); | |
| return '1=1 ' . $tq_sql['where']; | |
| } ); | |
| } | |
| $mods[] = $mod; | |
| return $mods; | |
| }, 20, 2 ); |
Questo snippet verifica che sia stato scelto un valore non vuoto dal menu a discesa. In tal caso, il nostro Mod viene creato e aggiunto alla Query.

