I have used a Yoast seo plugin and set primary category for product. But in front I cannot get primary category name.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Hi you can get using postmeta table.
$primary_cat_id=get_post_meta($product->id,'_yoast_wpseo_primary_product_cat',true);
if($primary_cat_id){
$product_cat = get_term($primary_cat_id, 'product_cat');
if(isset($product_cat->name))
echo $product_cat->name;
}
回答2:
I could not get the accepted answer to work. I modified this to fit my needs
$cat_name = ''; // I have this set in some shortcodes
if (!isset($cat_name) || $cat_name == '') {
if ( class_exists('WPSEO_Primary_Term') ) {
// Show the post's 'Primary' category, if this Yoast feature is available, & one is set. category can be replaced with custom terms
$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)) {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
} else {
$cat_name = $term->name;
}
} else {
$categories = get_the_terms(get_the_ID(), 'category');
$cat_name = $categories[0]->name;
}
}
I have edited a working example to be more self contained, I used it for custom taxonomy so used get_the_terms() instead of get_the_category(). This code has not been tested in its current state.