1

Apologies but I'm not quite sure how to title this post. When my custom taxonomies are searched nothing shows up after "Posted In" I'm not sure how to go about adding it the categories php below.

Any help is much appreciated, I think I need an if/else statement?

        <p class="post-info"><?php the_time('F j, Y'); ?> | by <a href="<?php echo get_author_posts_url(get_the_author_meta('ID')); ?>"><?php the_author(); ?></a> | Posted in

        <?php
            $categories = get_the_category();
            $separator = ", ";
            $output = '';

            if ($categories) {

                foreach ($categories as $category) {

                    $output .= '<a href="' . get_category_link($category->term_id) . '">' 
                    . $category->cat_name . '</a>'  . $separator;

                }
                echo trim($output, $separator);
                }
        ?>

</p>
0

get_the_terms() is the function you need to get terms of a custom taxonomy associated to your post.

It is similar (but not identical) to get_the_category() for the default category taxonomy.

[Edited to answer the first comment below]

Adapting the code you have for categories, here's how you can display either categories or terms:

<?php
    $categories = get_the_category();
    $separator = ", ";
    $output = '';

    if ($categories) {

        foreach ($categories as $category) {

            $output .= '<a href="' . get_category_link($category->term_id) . '">' 
            . $category->cat_name . '</a>'  . $separator;

        }
        echo trim($output, $separator);
    }
    elseif ( $terms = get_the_terms( get_the_ID(), 'my-custom-taxonomy' ) ) {

        foreach ( $terms as $term ) {

            $output .= '<a href="' . get_term_link( $term, 'my-custom-taxonomy' ) . '">' 
            . $term->name . '</a>'  . $separator;

        }
        echo trim( $output, $separator );
    }
?>

Don't forget to replace 'my-custom-taxonomy' (twice) with the actual slug for your taxonomy.

Note that by using this if/else structure, if a post has both a category and a term from the custom taxonomy, then only the category will show. One can just change the elseif to just if in case they want both to be displayed in such case.

References:

  • How do I add this as an else if to the above code?... so if its not a category, its a term – Ashley Feb 8 '18 at 15:04
  • I edited my answer above to answer this – Iceable Feb 8 '18 at 16:42
  • my hero! this is exactly what I needed, many thanks!! – Ashley Feb 8 '18 at 16:48
  • You're welcome! Please mark my answer as accepted if it helped :) – Iceable Feb 8 '18 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.