X

How to Display Posts From a Category on a Page

Snippets by IsItWP

Are you looking for a way to display posts from a category on a page? While there’s probably a plugin for this, we have created a quick code snippet that you can use to display posts from a category on a page in WordPress.

The need for this arose when you want to have a menu item called “news” on a WordPress site used as a CMS. It may not be easy to integrate a post category into your pages menu. What you could do is add a page called “news” and use a plugin to redirect the page to the category you want to show.

There is just one problem.

As soon as you are redirected to a category, the built-in conditional menu highlighting doesn’t work anymore which means that even if you were reading “news”, the menu item “news” in you menu wouldn’t be highlighted.

So this code displays the posts from your news-category but on a page (page.php or your own custom page template) and you can now enjoy the benefits of menu highlighting.

Instructions:

All you have to do is add this code to your theme’s page.php file or in a site-specific plugin:

<?php
$displayposts = new WP_Query();
  //get posts from your news category
  $displayposts->query('cat=5');
while ($displayposts->have_posts()) : $displayposts->the_post();
?>
<?php the_content('read more...'); ?>
<?php edit_post_link('edit', '', ''); ?>
<?php endwhile; ?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 28 best WordPress business themes for your website and how to fix the error establishing a database connection in WordPress.

Comments   Leave a Reply

  1. A situation where I want a post to have the category name as a link to a page of same categories post. Help!

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!