wordpress taxonomy query code example
Example 1: wp_query get by taxonomy
$the_query = new WP_Query( array(
'post_type' => 'Adverts',
'tax_query' => array(
array (
'taxonomy' => 'advert_tag',
'field' => 'slug',
'terms' => 'politics',
)
),
) );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_title(); //show post title
}
}
Example 2: wp query search
$query = new WP_Query( array( 's' => 'keyword' ) );
Example 3: search on taxonomy wordpress query
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');