在Wordpress中,我如何恢复到主要类别?
我正在使用下面的循环,如果所有三个都选中了,那么它就会恢复到最后一项。我想确保它是主要的类别。
<?php $term_list = wp_get_post_terms($post->ID, 'category', array("fields" => "names"));
foreach ($term_list as $term) {
$name = $term;
} ?>
发布于 2017-04-06 23:40:20
这不是原生的wordpress特性,而是Yoast SEO (see here)的特性。
您可以通过以下方式检查主要状态:
<?php
$term_list = wp_get_post_terms($post->ID, 'category', ['fields' => 'all']);
foreach($term_list as $term) {
if( get_post_meta($post->ID, '_yoast_wpseo_primary_category',true) == $term->term_id ) {
// this is a primary category
}
}
?>
如果您使用的是自定义分类,请使用meta_key
_yoast_wpseo_primary_CUSTOM_TAXONOMY
而不是。
发布于 2018-11-22 18:47:34
如果你使用的是“SEO框架”插件,而不是"Yoast SEO":
$taxonomy = 'category';
$post_id = get_the_ID();
$terms = wp_get_post_terms($post_id, $taxonomy, ['fields' => 'all']);
$primary_term = intval(get_post_meta( $post_id, '_primary_term_' . $taxonomy, true ));
foreach($terms as $term) {
if( $primary_term == $term->term_id ) {
// this is a primary category
}
}
参考文献:
发布于 2020-08-26 03:41:46
如果你使用Yoast插件索引和优化,接受的答案将不起作用。
$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 );
这将是正确的方法。
为了确保站点不会在Yoast被禁用时中断,您应该将代码包装在
if ( class_exists('WPSEO_Primary_Term') ) { }
https://stackoverflow.com/questions/43114986
复制相似问题