Primary Category Shortcode for Yoast
Adds a [primary_category] shortcode that shows the post's Yoast SEO primary category as a link, falling back to its first category.
Opens WPIDE on
Code
add_shortcode( 'primary_category', function ( $atts ) {
$atts = shortcode_atts( array( 'taxonomy' => 'category', 'link' => 'yes' ), $atts, 'primary_category' );
$post_id = get_the_ID();
$taxonomy = sanitize_key( $atts['taxonomy'] );
if ( ! $post_id || ! taxonomy_exists( $taxonomy ) ) {
return '';
}
$term_id = function_exists( 'yoast_get_primary_term_id' ) ? (int) yoast_get_primary_term_id( $taxonomy, $post_id ) : 0;
$term = $term_id ? get_term( $term_id, $taxonomy ) : null;
if ( ! $term instanceof WP_Term ) {
$terms = get_the_terms( $post_id, $taxonomy );
$term = ( $terms && ! is_wp_error( $terms ) ) ? $terms[0] : null;
}
if ( ! $term ) {
return '';
}
if ( 'no' === $atts['link'] ) {
return '<span class="primary-category">' . esc_html( $term->name ) . '</span>';
}
return '<a class="primary-category" href="' . esc_url( get_term_link( $term ) ) . '">' . esc_html( $term->name ) . '</a>';
} );
Notes
Use [primary_category link="no"] for plain text or taxonomy="product_cat" for another taxonomy.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.