• I’m working on some php to generate a list of links based on the categories of the current post. So far I have this, which works great for most cases:

    <?php $categories = get_the_category(); ?>
    <nav>
    <?php foreach ($categories as $category):?>
    <a href="<?php echo 'https://www.nameoflinkedsite.com/' . $category->slug . '-tickets' ?>">
    <?php echo $category->name . ' Tickets<br>' ?></a>
    <?php endforeach; ?>
    </nav>

    My only problem: I need to exclude certain categories, and get_the_category() doesn’t support this. I’ve tried a couple of solutions suggested elsewhere on the support forum, but none play nicely with the rest of my code. Any ideas?

    You can view the test page for this code here:

    http://www.fieldofschemes.com/1901/06/16/11239/ad-test-page/

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter nulldogmas

    (@nulldogmas)

    One thing I tried that looked promising:

    https://wordpress.org/support/topic/exclude-categories-from-the_category?replies=10#post-1638982

    Unfortunately, replacing get_the_category() with the_excluded_category() generates an error: Warning: Invalid argument supplied for foreach().

    Moderator bcworkz

    (@bcworkz)

    The error may have to do with the function being called is outside the loop’s variable scope, in which case a post ID is needed for get_the_category( $post_id ).

    The key feature is the conditional that verifies the category ID is not in an array before doing something. You can adapt your own code to use this, since your foreach apparently works 🙂

    <?php $categories = get_the_category();
    $excludedcats = array( 11, 22, 33, /*<-- category IDs to exclude */ ); ?>
    <nav>
    <?php foreach ($categories as $category):
      if ( !in_array($category->cat_ID, $excludedcats ) {?>
        <a href="<?php echo 'https://www.nameoflinkedsite.com/' . $category->slug . '-tickets' ?>">
        <?php echo $category->name . ' Tickets<br>' ?></a>
      <?php }
    endforeach; ?>
    </nav>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘excluding categories from get_the_category list’ is closed to new replies.