• Do you know how to exclude parent category from listing the posts?

    I will provide an example: On this page https://firm-guide.com/2013/official-shots-of-the-new-mercedes-benz-cla-revealed/ in the sidebar there are recent posts from category “cars”, but I want to display only posts from category “Mercedes-Benz” (which is a child category and “cars” is parent category).

    Currently I am using following code:

    <?php
    $cat = get_the_category();
    $cat = $cat[0];
    $posts = get_posts("category=" . $cat->cat_ID . "&numberposts=5");
    if( $posts ) :
    ?>
    
    <h3 class="widget-title">More on this category</h3>
    <?php foreach( $posts as $post ) : setup_postdata( $post ); ?>
    <a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>"><?php the_post_thumbnail('medium'); ?></a> <br>
    <div class="sidebar-product-meta">
    <a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a><br>
    <span style="font-size:10px;">Date posted: <?php the_date(); ?></span>
    </div>
    <?php endforeach; ?>

    Can somebody help me exclude the “cars” category so that only Mercedes-Benz posts are shown as related?

    Thank you

Viewing 5 replies - 1 through 5 (of 5 total)
  • get_posts accepts an exclude parameter, for example, if Mercendes-Benz had a category of id 20

    $cat = get_the_category();
    $cat = $cat[0];
    $posts = get_posts("category=" . $cat->cat_ID . "&numberposts=5&exclude=20");

    Thread Starter External11

    (@external11)

    Hi Andrew, thank you but I need to replace the number with a variable. I have a lot of categories…

    External, sorry I didn’t back to this earlier, let me play around with it on our dev server.

    Ok, your $cat object will include a parent value, so you can exclude off of that. For example:

    $cat = get_the_category();
    $cat = $cat[0];
    $posts = get_posts("category=" . $cat->cat_ID . "&numberposts=5&exclude=".$cat->parent);

    Thread Starter External11

    (@external11)

    Hi Andrew,
    I’ve modified the template, however the result is the same yet…
    Have you tested it?
    Thank you

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to exclude parent category from listing posts in sidebar’ is closed to new replies.