Tag Archives: page template

Displaying posts in a category as a page in wordpress

In this site the Life page only displays the posts in the category Life.
I did this in a manual way by creating a Page Template for the Life page. This gives you more control. The problem with this approach is that you have to do it again for a new theme.

In wordpress, individual pages can be set to use a specific custom Page Template (a PHP template file, e.g., life.php) that we create within our Theme. The custom Page Template can be assigned while creating a new page. This new Page Template will then override the default page.php Page Template in the Theme.
When loading a page, wordpress looks first for the assigned Page template, then the page.php and finally the index.php. The first one it finds will be used to display that Page. The template pages are situated in the theme’s directory which is at wp-content/themes/your-theme

In our case we need a Page Template that will be similar to the home page but displays only the posts in the required category.
So we will base our custom Page Template on index.php which is the Page Template of the home page.

We make a copy of  the index.php with the name mypage.php (or anything.php)

Add the following code to the top of it so that wordpress understands that it is a Page Template and identify its Template Name. This name will be displayed in the theme editor page.

<?php
/*
Template Name: MyPage
*/
?>

Now, we add the filter to display only the required category. This should be added just after the above Template Name code

<?php
if (is_home()) {
query_posts($query_string."&cat=3");
}
?>

In this code we display only category with id 3. The category id can be found out from the wordpress Edit Category pages by mouse hovering the required category and its id will be shown in the browser’s status bar.
Now to display more than one category use some thing like this
query_posts($query_string."&cat=2,6,17,38");

Create a blank page and assign this custom template to it. [Look for a drop-down labeled “Page Template” towards the bottom]

Thats all!

For more detailed information on Page Templates, visit this wordpress codex page