# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Plugin Integrations](https://wpide.com/library/category/integrations/)
- Tags: yoast, categories, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/yoast-primary-category-shortcode/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Primary Category Shortcode for Yoast" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
