1

I'm making a category archive template that works for all my categories. I need to dynamically set the 'category' parameter of WP_Query inside of this template to make it work.

How do I dynamically get a string of the current category page name to feed into the WP_Query? All the methods I've seen presupposed that I know my ID or slug. As this is an archive page, most WP functions will not return the archive page title but rather a post title.

The best option I've see is: $current_category = single_cat_title("", false);

But it still displays the title on my category.php page - maybe I'm doing something wrong with this?

  • is there a reason you can't use pre_get_posts to alter the main query? – Milo Jan 15 '16 at 22:10
  • Not familiar - would love to see how you use it. – serraosays Jan 15 '16 at 22:12
2

This is the only option I have found:

$current_category = single_cat_title("", false);
| improve this answer | |
1

To answer your question, get_queried_object and get_queried_object_id will give you all the info you need about most types of pages.

However- if you're creating a new query in the template to change some query parameters, then you should instead be using pre_get_posts to alter the main query before it's run. Then you can just run the regular loop in your template.

For example, changing posts_per_page on a category archive:

function wpd_category_query( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', 15 );
    }
}
add_action( 'pre_get_posts','wpd_category_query' );
| improve this answer | |

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.