Aleš Sýkora / March 24, 2022 / 0 comments

Get first term of current post in WordPress query

Post summary: 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. This snippet will get all terms assigned to the post with get_the_terms function. You can also…

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;
}

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

0 comments

Share Your Thoughts