Last active
December 8, 2022 21:42
-
-
Save jawinn/1b44bf4e62e114dc341cd7d7cd8dce4c to your computer and use it in GitHub Desktop.
Display Primary Category (Yoast's WordPress SEO)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get the Yoast primary category from its post meta value, and displays it, with HTML markup. | |
* If there is no primary category set, it displays the first assigned category. | |
* | |
* @param boolean $useCatLink Whether to link the category, if it exists | |
* @return void | |
*/ | |
function yourtheme_display_yoast_primary_category( $useCatLink = true ) { | |
// Retrieves post categories | |
$category = get_the_category(); | |
// If post has a category assigned. | |
if ( $category ) { | |
$category_display = ''; | |
$category_link = ''; | |
// Get post's 'Primary' category from post meta | |
$yoast_primary_key = get_post_meta( get_the_id(), '_yoast_wpseo_primary_category', TRUE ); | |
if ( !empty($yoast_primary_key) ) | |
{ | |
$term = get_term( $yoast_primary_key ); | |
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's 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="', esc_url($category_link), '">', esc_html_e($category_display), '</a>'; | |
echo '</span>'; | |
} else { | |
echo '<span class="post-category">', esc_html_e($category_display), '</span>'; | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
got it, I had to add $useCatLink = "true"; and worked great (thought only needed that to NOT display the link).
Thanks again, such a huge help!