Yoast-自定义分类-主要类别

时间:2019-05-21 作者:Rico Shaft

我有一个名为country的自定义分类法。我只想显示主要类别。我安装了yoast插件,这就是我设置主要类别的方式。

我正在使用我发现的这段代码来做同样的事情,但它适用于帖子类别,效果很好。

<?php
$primaryCat = new WPSEO_Primary_Term(\'category\', get_the_ID());
$primaryCat = $primaryCat->get_primary_term();
$primaryCat = get_cat_name($primaryCat);

$categories = get_the_category();
foreach( $categories as $category ) {
   $defaultCat = $category->name;
   $defaultCatLink = get_category_link( $category->term_id );
}

if ( $primaryCat !== "" ) {
   $cat = new WPSEO_Primary_Term(\'category\', get_the_ID());
   $cat = $cat->get_primary_term();

   $catName = get_cat_name($cat);
   $catLink = get_category_link($cat);

} else {
   $catName = $defaultCat;
   $catLink = $defaultCatLink;
}
?>

<h3><a href="<?php echo $catLink; ?>"><?php echo $catName; ?></a></h3>
如果有人能帮我找出如何获取主类别并将其显示为自定义分类法,我将不胜感激?

谢谢你抽出时间来看看我的问题!!

1 个回复
SO网友:Rico Shaft

我找到了这个,它很有效。向WP Munchies大声喊叫!https://wpmunchies.com/display-primary-category-using-yoasts-make-primary-feature/

<?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( \'event_cat\', 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_bloginfo(\'url\') . \'/\' . \'event-category/\' . $term->slug;
        } 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>\';
        }
    }

} 

相关推荐