Hello!
You can use this; it will support any post type:
$post_type = get_post_type();
$id = get_the_ID();
$taxonomy = current( get_object_taxonomies( $post_type, 'objects' ) )->name ?? false;
$primary_term_id = function_exists( 'tsf' ) ? tsf()->get_primary_term( $id, $taxonomy ) : 0;
$primary_term_id = $primary_term_id ?: ( get_the_terms( $id, $taxonomy )[0]->term_id ?? null );
if ( $primary_term_id ) {
$term = get_term( $primary_term_id, $taxonomy );
echo $term->name ?? '';
}
Or, if you prefer it simpler (but it won’t support every post type), you can use this instead:
$cat = ( function_exists( 'tsf' ) ? tsf()->get_primary_term( get_the_id(), 'category' ) : null ) ?: ( get_the_category()[0] ?? null );
echo $cat->cat_name ?? '';
Here is the condensed code from above explained:
// If TSF exists, get the primary category.
$cat = function_exists( 'tsf' ) ? tsf()->get_primary_term( get_the_id(), 'category' ) : false;
// If a primary category is not found, use WP's function to get the first (0) category -- if none is found, set to null.
$cat = $cat ?: get_the_category()[0] ?? null;
// If the cat is found, echo name; otherwise echo ''.
echo $cat->name ?? '';