小智 14
Yoast SEO 插件现在有一个专门的功能yoast_get_primary_term_id()——用于获取主要术语的 ID:
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );
Run Code Online (Sandbox Code Playgroud)
然后您可以使用get_term()来获取WP_Term对象:
// Will return `false` if no primary term has been set
$primary_term_id = yoast_get_primary_term_id( 'taxonomy_slug', $post_id_or_object );
if ( $primary_term_id ) {
/** @var WP_Term $primary_term */
$primary_term = get_term( $primary_term_id );
}
Run Code Online (Sandbox Code Playgroud)
对于那些您只需要术语名称的场景,您可以使用yoast_get_primary_term():
// Will return an empty string if no primary term has been set
$primary_term_name = yoast_get_primary_term( 'taxonomy_slug', $post_id_or_object );
Run Code Online (Sandbox Code Playgroud)
小智 12
嗨,你可以使用postmeta表.
$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;
}
Run Code Online (Sandbox Code Playgroud)
我无法获得公认的工作答案。我修改了它以满足我的需求
$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;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经编辑了一个工作示例以使其更加独立,我将其用于自定义分类法,因此使用了get_the_terms()而不是get_the_category()。该代码尚未在其当前状态下进行过测试。
| 归档时间: |
|
| 查看次数: |
9559 次 |
| 最近记录: |