Last active
September 29, 2022 08:20
-
-
Save accrane/6334e078e9cc9b140de395f0f197c66d to your computer and use it in GitHub Desktop.
Using Yoast, "Make Primary Category" for Custom Taxonomies
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 | |
// Fill in your custom taxonomy here | |
$yourTaxonomy = 'CUSTOM_TAXONOMY'; | |
// SHOW YOAST PRIMARY CATEGORY, OR FIRST CATEGORY | |
$category = get_the_terms( $postId, $yourTaxonomy ); | |
$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( $yourTaxonomy, 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_term_link( $term->term_id ); | |
} else { | |
// Yoast Primary category | |
$category_display = $term->name; | |
$category_link = get_term_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_term_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.'">'.$category_display.'</a>'; | |
echo '</span>'; | |
} else { | |
echo '<span class="post-category">'.$category_display.'</span>'; | |
} | |
} | |
} |
A hard coded version of the custom taxonomy is on line 15 - consider changing to:
$wpseo_primary_term = new WPSEO_Primary_Term( $yourTaxonomy, get_the_id() );
Also category_link has a hard coded element too on line 21 - consider changing to:
$category_link = get_term_link( $term->term_id );
Both suggestions seem to work for me in a single use case, so thorough testing would be required before adopting.
Lol, thanks all. Had no idea people were using stuff I simply saved for myself!
Thanks for the suggestions!
@jmslbam - what do you consider a proper PHP comment should be there? Describing what is going to happen?
Sorry mate, that was 2017, really don't have a clue anymore hahaha.
But thank you for the code 😄 have a good day!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suggest you add proper PHP comment before