Display entire category in a drop-down list

It is a basic WordPress feature to have categories organized on your blog. While you can easily create new categories, modify them and fill with different posts of your own, delete them or reorganize, displaying posts might be a trickier thing to do.

Yes, WordPress automatically creates pages for each category on your site. Once you load the page dedicated to a certain category, WordPress will instantly load latest posts from it. And while you can choose a category widget which will show all categories, you might be interested in listing all posts from only one category.

If you don’t want to deal with additional plugins which can help you organize categories or if you’re working on a new theme, modifying an existing one, etc. you might be interested in the code we’re about to show you.

This code will take the category ID which you place in the variable and then find all published posts from it. The code will create a drop-down list where a user can easily browse through sorted posts. Once a user chooses a post, clicking on a “Go” button will load selected post.

Create a drop-down list and load posts from a category:

  1. Open sidebar.php or wherever you want to display the list
  2. Copy and paste the following code:
  3. <?php
    $cat_id = get_cat_ID('uncategorized');
    $args=array(
    'cat' => $cat_id,
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
    ?>
    <form name="jump">
    <select name="menu">
    <?php
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <option value="<?php the_permalink() ?>"><?php the_title(); ?></option>
    <?php
    endwhile;
    }
    ?>
    </select>
    <input type="button" onClick="location=document.jump.menu.options[document.jump.menu.selectedIndex].value;" value="Go">
    </form>
    <?php
    wp_reset_query();
    ?>
    
  4. Change category slug on the 2nd line
  5. Save changes

Now you can reload your homepage and see that there is a new list added on the sidebar or wherever you put the code. This list will contain all posts from the category you have selected.

If you like the list and you want to keep it on your site, you can go on and start modifying the looks of it via CSS code. Similarly, you can show the most commented posts from a single category.

If you want to do more with your blog, learn more about WordPress, blogging, and level up your webmaster skills with our resources.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *