WordPress.org

Ready to get started?Download WordPress

Forums

Show Related Categories (6 posts)

  1. chooseamc
    Member
    Posted 2 years ago #

    In the list of posts (on a portfolio page) I want to list the other categories that post belongs to, but exclude the current category. Tried this code:

    <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' - '; } ?> //shows each category name with a dash afterwards
    
    The cat_name is <?php {echo $category->cat_name . '';} ?> //only ever shows the highest alpha category
    
    <?php if (($category->cat_name) != $et_page_title) //this variable contains current page category as its title
    
    echo '<a href="http://www.domain.com/'.$category->cat_name.'">'.$category->cat_name.'</a>';
    
    else echo "Same name as Title"; ?>

    So, what happens is, the category that gets populated is the highest alpha category. If that's the same as the current title, I get "Same name as Title."

    Is there a better way to show a list of categories, excluding the current category? There must be!

  2. Unconformed
    Member
    Posted 2 years ago #

    have us tried a widget?

  3. chooseamc
    Member
    Posted 2 years ago #

    Thanks but - everything seems to be posts related to a category and not categories related to a post. Plus, I need to embed the code in the page so that it displays properly. Most widgets are for sidebars (though if I found one, I could always grab the code and reuse it).

    Hoping I'm just missing something simple as what I have above is very close to what I need - just that the $category->cat_name is always only the highest category in the alphabet.

  4. esmi
    Forum Moderator
    Posted 2 years ago #

    I don't think you're going to find anything much better. You might find slight coding variations but, ultimately, it's going to come down to a foreach loop that skips the current category.

  5. chooseamc
    Member
    Posted 2 years ago #

    Thanks but the foreach loop variable ($category->cat_name) isn't returning all the categories unless I concantenate it. That's the only thing stopping me at this point.

  6. chooseamc
    Member
    Posted 2 years ago #

    I ended up figuring this out on my own. Works great if you are using a portfolio type theme and want to display other categories the post is assigned to but exclude the current category. Here is the code I used:

    '<?php foreach((get_the_category()) as $category) { if (($category->cat_name) != $et_page_title) : echo 'cat_name.'">'.$category->cat_name.''; endif; } ?>'

    I already had access to the current category in this variable: $et_page_title. You may need additional code to trap your current category.

Topic Closed

This topic has been closed to new replies.

About this Topic