WPDD

WordPress Develop & Design

Get Yoast Primary Category

Written by

in

WordPress Yoast plugin.
how to get only one category and if selected (Primary Category) Primary than get the (Primary Category) Primary selected

function display_terms_name( $taxonomy ) {
    $post_id = get_the_ID(); // Get the current post ID
    $primary_category = '';
    $default_category_links = '';

    // Get all the terms for the post (categories in this case)
    $terms = get_the_terms( $post_id, $taxonomy );

    // If terms exist and no errors
    if ( $terms && ! is_wp_error( $terms ) ) :
        
        // If the Yoast SEO plugin is active and the WPSEO_Primary_Term class exists
        if ( class_exists( 'WPSEO_Primary_Term' ) && $taxonomy === 'category' ) {
            // Get the primary category ID
            $primary_term = new WPSEO_Primary_Term( 'category', $post_id );
            $primary_category_id = $primary_term->get_primary_term();
            
            // If a primary category is set
            if ( $primary_category_id ) {
                $primary_category = get_category( $primary_category_id );
                
                // Display the primary category and limit to one
                echo '<ul>';
                echo '<li><a href="' . esc_attr( get_term_link( $primary_category->slug, $taxonomy ) ) . '">' . __( $primary_category->name ) . '</a></li>';
                echo '</ul>';
                
                return; // If primary category exists, stop further execution
            }
        }

        // If no primary category is set, loop through all categories (or terms)
        // but only display the first one
        foreach ( $terms as $term ) {
            echo '<ul>';
            echo '<li><a href="' . esc_attr( get_term_link( $term->slug, $taxonomy ) ) . '">' . __( $term->name ) . '</a></li>';
            echo '</ul>';
        }

    endif;
}