Skip to content

Instantly share code, notes, and snippets.

@akshay-sihag
Created January 14, 2020 21:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akshay-sihag/97938e6e8e318d0ab59b437f44b8b6f1 to your computer and use it in GitHub Desktop.
Save akshay-sihag/97938e6e8e318d0ab59b437f44b8b6f1 to your computer and use it in GitHub Desktop.
Display Primary Category (Yoast's WordPress SEO) with the help of a shortcode
// Creating Shortcode to display Yoast SEO Primary Category
// Add Shortcode
function get_yoast_primary_cat() {
$category = get_the_category();
$useCatLink = true;
// If post has a category assigned.
if ($category){
$category_display = '';
$category_link = '';
if ( class_exists('WPSEO_Primary_Term') )
{
// Show the post's 'Primary' category, if this Yoast feature is available, & one is set
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
$term = get_term( $wpseo_primary_term );
if (is_wp_error($term)) {
// Default to first category (not Yoast) if an error is returned
$category_display = $category[0]->name;
$category_link = get_category_link( $category[0]->term_id );
} else {
// Yoast Primary category
$category_display = $term->name;
$category_link = get_category_link( $term->term_id );
}
}
else {
// Default, display the first category in WP's list of assigned categories
$category_display = $category[0]->name;
$category_link = get_category_link( $category[0]->term_id );
}
// Display category
if ( !empty($category_display) ){
if ( $useCatLink == true && !empty($category_link) ){
echo '<span class="post-category">';
echo '<a href="'.$category_link.'">'.htmlspecialchars($category_display).'</a>';
echo '</span>';
} else {
echo '<span class="post-category">'.htmlspecialchars($category_display).'</span>';
}
}
}
}
add_shortcode( 'yoast-primary-category', 'get_yoast_primary_cat' );
@akshay-sihag
Copy link
Author

Use Case

Now use shortcode [yoast-primary-category] to display the primary category anywhere you want

@toby12222
Copy link

it's possible display primary product (woocommerce) with a shortcode? could you help me? sorry my bad english

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment