WordPress: creare un motore di ricerca per le tassonomie dei custom post type

WordPress: creare un motore di ricerca per le tassonomie dei custom post type

Creare un motore di ricerca per le tassonomie dei custom post type è relativamente semplice in WordPress.

Per iniziare creiamo una classe per generare il form con i termini della tassonomia di riferimento all'interno di elementi select:


<?php
class My_Custom_Search {
	public function __construct() {

	}

	public function createSelectBox( $tax ) {
		$terms = get_terms( $tax );
		$html = '<select name="'. $tax .'">';
		$html .= '<option value="">'. ucfirst( $tax ) .'</option>';
		foreach ( $terms as $term ) {
	   		$html .= '<option value="' . $term->slug . '">' . $term->name . '</option>';
		}
		$html .= '</select>';
		return $html;
	}

	public function createForm( $page_id, $tax ) {
		$page_url = get_permalink( $page_id );
		$html = '<form method="post" action="' . $page_url . '">';
		$taxonomies = get_object_taxonomies( $tax );
		foreach( $taxonomies as $tax ) {
			$html .= $this->createSelectBox( $tax );
		}
		$html .= '<p><input type="submit" value="' . __( 'Cerca', 'miotema' ) . '" /></p>';
		$html .= '</form>';

		return $html;
	}
}

function my_create_custom_search_form( $page_id, $tax_name ) {
	$search = new My_Custom_Search();
	echo $search->createForm();
}

Quindi includiamo il codice in functions.php:


require_once( 'My_Custom_Search.php' );

La funzione my_create_custom_search_form() accetta due parametri: l'ID della pagina che mostrerà i risultati della ricerca e la tassonomia principale del custom post type.


<?php 
// Genera il form nel tema

my_create_custom_search_form( 12, 'tipologie-immobili' ); 
?>

Infine creiamo il template di pagina (qui riassunto) assemblando una query con relazione AND. Prima di farlo ci assicuriamo che i termini esistano e abbiano un valore eseguendo un loop sull'array superglobale $_POST:


<?php
/* Template Name: Custom Search */

$list = array();
$item = array();
$args = array();

foreach( $_POST as $key => $value ) {
	if( $value != '' ) {
		$item['taxonomy'] = htmlspecialchars( $key );
		$item['terms'] = htmlspecialchars( $value );
		$item['field'] = 'slug';
		$list[] = $item;
	}
}

$cleanArray = array_merge( array( 'relation' => 'AND' ), $list );

$args['post_type'] = 'immobili';
$args['showposts'] = 10;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args['paged'] = $paged;
$args['tax_query'] = $cleanArray;

$results = new WP_Query( $args );

if( $results->found_posts > 0 ) {
	// Loop
} else {
	// Nessun risultato	
}
?>

Torna su