WordPress: Changing query_posts category according to page

I have a custom page template in WordPress which has a loop to display posts, this is currently filtered by a category using

<?php query_posts( array ( 'category_name' => 'holidays' ) ); ?>

followed by the loop. As there are many different pages using the same template but all needing a different category of post. I would like to make the ‘holiday’ part vary depending on what page you are on. Is this possible to add a condition and how? Otherwise I assume I would have to create many different templates for each page?

Related posts

Leave a Reply

2 comments

  1. Another way you could do this is with is_page().

    For example:

    <?php if (is_page(pageIDgoesHere)) {
        $cat = 'holiday';
    } elseif (is_page(pageIDgoesHere) {
        $cat = 'anotherCategoryHere';
    }
    ?>
    

    You could put this above your query_posts() and then use:

    query_posts(array('category_name' => $cat,));

    You could repeat the below elseif as many times as you need to:

    elseif (is_page(pageIDgoesHere) {
        $cat = 'anotherCategoryHere';
    }
    

    Just use the integer ID of the page in place of pageIDgoesHere and set the desired category name where you see anotherCategoryHere.

    This would alleviate having to add a query string to your page URLs.

  2. You can add $_GET attribute to your script.

    $cat = $_GET['category'];
    
    query_posts( array ( 'category_name' => $cat ) ); 
    

    Then you access the page like this:

    http://sitename.com/yourpage.php?category=holiday
    

    Where “holiday” is the category.