Thursday, March 24, 2022
The Great Tit
Updated: 24. 3. 2022, Added: 24. 3. 2022

Get first term of current post in WordPress query

If you want to display only one first term assigned to your post, add this code. It will add a link to the category with CSS class with category slug, so you can style it separately from other categories.

<?php
    global $post;
    $terms = get_the_terms( $post->ID, 'category' );
    if ( !empty( $terms ) ) {
    // get the first term data
    $catname = $terms[0]->name;
    $catslug = $terms[0]->slug;
    $catlink = get_term_link( $terms[0] );?>
<a href="<?=$catlink?>" class="category-link category-<?=$catslug?>"><?=$catname?></a>
<?php
}
?>

This snippet will get all terms assigned to the post with get_the_terms function. You can also change the slug of taxonomy. I am using category taxonomy here. Then, if post has terms assigned it will save the name of first value and slug and of course - the link with get_term_link function.

Then it displays the link in HTML. You can use this code in Oxygen Code Block inside repeater, but it doesn't render in builder (don't know why).

You can also use array_shift, but be aware about shifting big amounts of data in array. It can slow down the whole process.

$terms = get_the_terms( $post->ID, 'category' );
if ( !empty( $terms ) ){
    // get the first term
    $term = array_shift( $terms );
    echo $term->slug;

    echo $term->name;
}
Did I help you? Support me on Patreon!
Beep this article to your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram