如何通过WordPress中的Yoast seo插件获取主要类别集

use*_*744 5 wordpress

我使用了Yoast seo插件并为产品设置了主要类别.但在前面我无法获得主要类别名称.

小智 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)

  • 这是 2021 年的答案,应该被接受为已批准的答案。 (2认同)

小智 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)

  • 对于对此有疑问的任何人,请记住为您的分类法更新该标签。本示例使用“ _yoast_wpseo_primary_product_cat”。如果您的分类标准为“城市”,则应使用“ _yoast_wpseo_primary_city”。 (2认同)

Sam*_*Sam 5

我无法获得公认的工作答案。我修改了以满足我的需求

$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()。该代码尚未在其当前状态下进行过测试。