UPDATE: Moving to PHP8 from PHP7.4, there was a problem with the format of the original filter form throwing an error. I have not tested this code specifically, but I resolved the issue where it was a problem on active websites and updated this to match.
Filter News by Category
<form action="" method="GET" id="news">
<?php
$categories = get_categories('taxonomy=news-category&post_type=news');
?>
<select name="newscat" id="newscat" onchange="submit()">
<option value="">Show all (default)</option>
<?php
foreach ($categories as $category) :
echo '<option value="'.$category->name.'"';
if(isset($_GET['newscat']) && ($_GET['newscat'] == $category->name)) { echo ' 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
endwhile;
else :
echo '<p>There are no news items in that category.</p>';
endif;
wp_pagenavi( array( 'query' => $newslist ) );
wp_reset_query();