WordPress.org

Ready to get started?Download WordPress

Forums

Excluding a category from get_the_category to create relate posts (2 posts)

  1. Jacktionman
    Member
    Posted 1 year ago #

    Hi there,

    I'm having a lot of trouble creating a related articles section in my theme.

    Basically, my posts go in their home category (soccer, for example), and some of them also go into a featured category. However, when I use code below to try to call related posts from soccer, I also get posts from the featured category, as the function is using get_the_category to return both categories, rather than just soccer:

    <?php
    global $post;
    $categories = get_the_category();
    $category = $categories[0];
    $cat_ID = $category->cat_ID;
    $myposts = get_posts("numberposts=4&offset=1&category=$cat_ID");
    ?>
    <?php foreach($myposts as $post) :?>
    <div class="four-box"><?php the_title(); ?></div>
    <?php endforeach; ?>

    I'm trying to get it so that all posts from soccer are featured, and that it excludes posts that are solely in featured.

    This has to work for other categories as well (not just soccer), so just directly referencing the ID is not possible. I think I need some sort of "get the categories of this post & ignore posts only in the featured category" command, but I can't seem to work it out.

    I'd be really grateful if anyone could help - I'm going a little mad (and I've been staring at the code for far too long!). Thanks!

  2. Chris
    Member
    Posted 1 year ago #

    I would recommend to write a custom loop instead using get_posts (http://codex.wordpress.org/Class_Reference/WP_Query).

    There you have more options, like for example category__in (array) or category__not_in (array) and many more.

Topic Closed

This topic has been closed to new replies.

About this Topic