When your website means business.

PHP, WP Query, WP/CP | Type: PHPFilter Custom Post Type by Taxonomy

Can be found on an Evo blog post with more explanation at the link below. Note: this throws an ‘unknown index’ error.

<h4>Filter News by Category</h4>
<form id="newslist" action="" method="GET"> <!--build the dynamic form-->
<select id="news" name="newscat" onchange="submit();">
    <option value="" <?php echo ($_GET['newscat'] == '' ) ? ' selected="selected" ' : ''; ?>>Show all news</option> 
    <?php $categories = get_categories('taxonomy=news-category&post_type=news'); 
    foreach ($categories as $category) : 
        echo '<option value="'.$category->name.'"'; 
        echo ($_GET['newscat'] == ''.$category->name.'') ? ' selected="selected"' : ''; 
        echo '>'.$category->name.'</option>'; 
    endforeach; 
    ?> 
</select> 
</form> 

<?php // let the queries begin 
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; 
if( !isset($_GET['newscat']) || '' == $_GET['newscat']) { // if nothing selected or 'show all' selected 
$newslist = new WP_Query( array( 
    'post_type' => 'news', 
    'posts_per_page' => 8, 
    'orderby' => 'DATE', 
    'paged' => $paged 
) ); 

} else { //if select value exists, the query that compares $_GET value and taxonomy term (name) 
$newscategory = $_GET['newscat']; //get filter value 
$newslist = new WP_Query( array( 
    'post_type' => 'news', 
    'posts_per_page' => 8, 
    'orderby' => 'DATE', 
    'paged' => $paged, 
    'tax_query' => array( //the taxonomy query 
        array( 
        'taxonomy' => 'news-category', 
        'field' => 'name', 
        'terms' => $newscategory 
        ) 
     ) 
)); 
} 

if ($newslist->have_posts()) : while ( $newslist->have_posts() ) : 
$newslist->the_post(); 
?> 

SHOW RESULTS

<?php endwhile; 
else : 
echo '<p>There are no news items in that category.</p>'; 
endif; 
?>  
<?php wp_pagenavi( array( 'query' => $newslist ) ); ?> 
<? wp_reset_query(); ?>

Reference Links

We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept