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.
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.