假设您使用的是Yoast SEO插件,我还没有对此进行测试,但我认为您可以这样做:(来源https://pretagteam.com/question/get-primary-category-if-more-than-one-is-selected)
/*
Checks for a yoast primary category, if it exists move the category to the first position in the $categories array.
*/
function yoast_primary_cat_as_first_cat($categories) {
// Check if yoast exists and get the primary category
if ($categories && 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 no error is returned, get primary yoast term
$primary_cat_term_id = (!is_wp_error($term)) ? $term->term_id : null;
// Loop all categories
if ($primary_cat_term_id !== null) {
foreach($categories as $i => $category) {
/* Move the primary category to the top of the array
and leave the rest of the categories in the order they were in */
if ($category->term_id === $primary_cat_term_id) {
$out = array_splice($categories, $i, 1);
array_splice($categories, 0, 0, $out);
break;
}
}
}
}
return $categories;
}
add_filter(\'get_the_categories\', \'yoast_primary_cat_as_first_cat\');