• Resolved axel

    (@axeldittmann)


    Hey there! For now we are using the following easy PHP code to show the category name:

    <?php $cat = get_the_category(); echo $cat[0]->cat_name; ?>

    How does the PHP code look like to show the TSF primary category here instead?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Sybre Waaijer

    (@cybr)

    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 ?? '';
    Thread Starter axel

    (@axeldittmann)

    Awesome, that works! Thank you for the great plugin – and also for your quick response on this issue! ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Show primary category via PHP’ is closed to new replies.