0

Taking on legacy data I have the following structure

-Top level category (category)

-- Sub category (report)

--- Post

I want to get all posts in a particular top level category.

The problem is all the posts are only assigned to Sub Categories, not their top level categories.

I've tried the following:

function getPostsInCategory($category) {

    return get_pages(array(
        'post_status'   => 'publish',
        'post_type'     => 'post',
        'child_of'      => $category, // e.g '3'
        'numberposts'   => -1
    ));
}

I use get_pages instead of get_posts because it seems to support heirachy better.

How can I get all posts that are in a "report" that is a child of my chosen category?

  • You're implementing categories as pages? In your example "Top level category" is a category or a page? – Krzysiek Dróżdż Jun 25 '13 at 11:37
  • ignore the pages aspect, these are normal categories and posts we are referring to, however I read you can still use get_pages to get posts – Titan Jun 25 '13 at 11:41
1

You should use get_posts or (even better) custom WP_Query to query posts.

You can use get_pages to do this, but get_pages can't use category (or other taxonomies - just check it in WP sources) to filter results.

So your function should look like this:

function getPostsInCategory($category) {

    return get_posts(array(
        'post_status'   => 'publish',
        'category'      => $category, // e.g '3'  catgory is passed as 'cat' param of WP_Query, so it will display posts from children categories as well
        'posts_per_page'   => -1
    ));
}
  • Oh god I feel so stupid, I didn't realise it would find grandchildren, I thought the posts would have to be directly in that category for it to work. Thank you :) – Titan Jun 25 '13 at 12:26

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.