Primary Category Shortcode for Rank Math
Adds a [rm_primary_category] shortcode that shows the primary category chosen in Rank Math, or the first category when none is set.
Opens WPIDE on
Code
add_shortcode( 'rm_primary_category', function ( $atts ) {
$atts = shortcode_atts( array( 'taxonomy' => 'category', 'link' => 'yes' ), $atts, 'rm_primary_category' );
$post_id = get_the_ID();
$taxonomy = sanitize_key( $atts['taxonomy'] );
if ( ! $post_id || ! taxonomy_exists( $taxonomy ) ) {
return '';
}
// Rank Math stores the primary term as rank_math_primary_{taxonomy}.
$term_id = (int) get_post_meta( $post_id, 'rank_math_primary_' . $taxonomy, true );
$term = $term_id ? get_term( $term_id, $taxonomy ) : null;
if ( ! $term instanceof WP_Term || ! has_term( $term->term_id, $taxonomy, $post_id ) ) {
$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 link="no" for plain text, or taxonomy="product_cat" for WooCommerce products.
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.