Forums

How to get Category Parent when post has multiple categories (2 posts)

  1. wasnotwas
    Member
    Posted 4 years ago #

    I want to issue a query_post when my posts are under a certain category parent. I am having problems when the posts are filed under more than one category. The
    get_the_category() request always returns that the post is a child of a parent.

    For instance.
    If post A, is under category 16 and 10, and category 16 is a child of category 6. All posts that are children of category 6 I want to be sorted ASC. I use get_the_category() to find the parent. I use foo.com/?cat=16 as the URL. That will work.

    When I use foo.com/?cat=10. I get incorrect posts being shown, and sorted ASC, as the get_the_category() still returns the parent as category 6, when it should be 0.

    Is there a way around this?

  2. wasnotwas
    Member
    Posted 4 years ago #

    This code outside the loop works.

    <?php // This code checks to see if the parent is 6. There may be more than one category assigned to a post.
    $savecat=$cat; // savecat is the cat found in the URL it need to be checked againt the possible categories for the post
    foreach((get_the_category()) as $cat) {
    if ( $cat->cat_ID == $savecat ): // Only when they agree will we check the parent
    if ( $cat->category_parent=='6' ):
    $query=$query_string . '&order=ASC'; // Then change the Sort order ASC if 6 is parent
    query_posts($query);
    endif;
    endif;
    }
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags