0

Is it possible to use a variable for the 'category_name' parameter?

I have three pages: red, yellow, and blue. I have multiple posts that are categorized in three categories: red, yellow, and blue. On the red page, I wish to display information from the posts in the red category; the same goes for yellow and blue.

I can do this easily if I create three different page templates with these $args at the beginning of the loops:

$args = array(
    'category_name' => 'red'
);  

$the_query = new WP_Query( $args );

or

'category_name' => 'yellow'

or

'category_name' => 'blue'

Rather than make three separate page templates, is it possible to create one, in which the 'category_name' parameter is set to the page's title (so the 'red' page would result in 'red' being dynamically set to the 'category_name' parameter)?

While this doesn't work, hopefully it illustrates what I'm trying to do:

$title = the_title()

$args = array(
    'category_name' => $title
);  

Thanks for taking the time to look at this!

  • @PieterGoosen Can you explain why you think this is a duplicate? That other question doesn't ask about variables for the 'category_name' parameter. – minimographite Oct 1 '14 at 8:11
0

Yes you can pass the variable in category_name. But I think it should be get_the_title() instead of the_title().

$title = get_the_title();

$args = array(
    'category_name' => $title
);

Try this. But remember category_name only accepts category slug, not category name.

You can also use following method if your page title/slug are different. And I think it's better.

if ( is_page( 'Page Name One' ) ) {

    $cat_title = 'red'; // should be category slug

} elseif ( is_page( 'Page Name Two' ) ) {

    $cat_title = 'yellow'; // should be category slug

} elseif ( is_page( 'Page Name Three' ) ) {

    $cat_title = 'blue'; // should be category slug

}

$args = array(
    'category_name' => $cat_title
);
  • Bravo! Thank you so much. This answers my question precisely. – minimographite Oct 1 '14 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.