I am working for a client that has requested a drop down list for some categories within a page, i.e. click on the link and a list drops down to select the page you want to view. Everything I seem to be finding is telling me how to create the drop down in the nav bar, that is not what I need. Any help is greatly appreciated...
1 Answer
I'm not sure if you have pages with categories, but I can show you a example using posts instead.
Dropdown Filter from posts by category:
<?php
$url = get_home_url();
$category_slug = 'my-new-category'; //remember to get the slug
$posts_by_category = new WP_Query([
'post_type' => 'post',
'category_name' => $category_slug,
'nopaging' => true
]);
if ( $posts_by_category->have_posts() ) :
$dropdown = '<select onchange="window.location.href = this.value" name="posts-by-category">';
while ( $posts_by_category->have_posts ) : $posts_by_category->the_post();
$dropdown .= sprintf('<option value="%s?p=%s">%s</option>', $url, get_the_ID(), get_the_title() );
endwhile;
$dropdown .= '</select>';
endif; wp_reset_postdata();
echo $dropdown;
?>