0

I've ran into trouble, i do not understand how to make my custom query respect the current category i'm browsing.

Lets say i'm in category "test1" and i have this custom query loop:

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;   
$query_args = array( 
    'post_type' => 'post',
    'post_status' => array('private', 'publish'),
    'posts_per_page' => 20,
    'paged' => $paged,
); 
$the_query = new WP_Query( $query_args );   
   if ( $the_query->have_posts() ) :     
       while ( $the_query->have_posts() ) : $the_query->the_post();

This will take all posts that are private/publish and show them on all pages, even if i am browsing a category..... How do i add some a custom query that respect the current category?

If i add cat'=> '1', and specify a category, it obviously only grabs the category i specify.

I've desperately tried to use in house functions such as:

$category = get_queried_object();
echo $category->term_id;

inside the 'cat'=> '', statement but that obviously doesn't work. I've also tried to use php if / else statments inside the array in hopes of being able to generate the category id based on where i am browsing on the site such as:

if (is_category(1)) { 
'cat' => '1', } else { 'cat' => '12', }

How do i go about solving this?

4
  • Assuming you are doing more than just trying to display posts for a category, yes? Otherwise you would just use the category archive template and not need a query at all. codex.wordpress.org/Category_Templates
    – jdm2112
    Commented Mar 3, 2016 at 22:47
  • I am trying display published and private posts using this query on all pages except tag pages, i have solved so tag pages use a different query (the original one) but my custom query will not take the category into consideration, i've gotten a little bit further since i posted: i added $category = get_the_category(); $category_id = $category[0]->cat_ID; 'cat' => $category_id, to my custom query and now it takes the category into consideration, only one problem, if a post has more than 1 category in current category it also takes those categories into consideration, this is not what i wanted. Commented Mar 3, 2016 at 22:51
  • i guess i could create one template file per category and insert the query hardcoded into each category page but it's a little unpractical if i make changes to the theme later i have to edit as many files as i have categories Commented Mar 3, 2016 at 22:55
  • if you don't actually need an additional query, you can use pre_get_posts to modify the main query without editing the template.
    – Milo
    Commented Mar 3, 2016 at 23:25

1 Answer 1

-1

I ended up using the built in template hierarchy to solve this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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