Skip to content

Instantly share code, notes, and snippets.

@dariodev
Last active February 15, 2019 18:28
Show Gist options
  • Save dariodev/19446e6358c599f4854bc1062da4e60f to your computer and use it in GitHub Desktop.
Save dariodev/19446e6358c599f4854bc1062da4e60f to your computer and use it in GitHub Desktop.
WordPress get the primary category for a post (Yoast’s “Primary” Category )
<?php
// Show Yoast’s “Primary” Category. Fallback to first category.
$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 WP 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 ( true === $usecatlink && ! empty( $category_link ) ) {
echo '<span class="entry-terms category" itemprop="articleSection">';
echo '<a href="' . esc_url( $category_link ) . '">' . esc_html( $category_display ) . '</a>';
echo '</span>';
} else {
echo '<span class="entry-terms category" itemprop="articleSection">' . esc_html( $category_display ) . '</span>';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment