默认情况下,WordPress不会在上次更新分类术语时保留数据库值。
所以,为了实现您的目标,一种解决方案是循环浏览您的帖子,并按日期或上次修改的时间排序。在循环过程中,您可以将分配给职位的术语/类别存储在变量中。最后,你会有很多你想要的“新鲜类别”。
在下面的代码中,我使用的是“product”post类型和“product\\u cat”分类法。你可能想把它们分别改为“post”和“category”。
function display_terms_with_fresh_posts() {
$out = \'\';
$args = array(
\'post_type\' => \'product\', // CHOOSE YOUR POST TYPE!!!
\'posts_per_page\' => -1,
\'order\' => \'DESC\',
\'orderby\' => \'date\' // Use \'date\' to get the last created or \'modified\' to get last updated.
);
$q = new WP_Query( $args );
// Set the var which will keep the wanted terms.
$fresh_terms = array();
// Set the counter which will help us to get just as many categories as we want.
$i = 0;
if ( $q->have_posts() ) :
while ( $q->have_posts() ) : $q->the_post();
$post_id = get_the_ID();
$taxonomy = \'product_cat\'; // CHOOSE YOUR TAXONOMY!!!
$post_terms = get_the_terms( $post_id, $taxonomy );
if ( !$post_terms )
continue;
foreach ( $post_terms as $t ) {
if ( !in_array( $t->term_id, $fresh_terms ) ) {
// Here we choose how many categories to display. In this case I chose 5, that\'s why the var $i needs to be at least greater than 4.
if ( $i > 4 ) {
$stop_loop = true;
break;
}
else {
$fresh_terms[] = $t->term_id;
$i++;
}
}
// IMPORTANT! If u want to get all the terms assigned to each post u need to remove break from here.
// This means that using break we will get just one term for each post.
break;
}
if ( isset( $stop_loop ) )
break;
endwhile;
else:
$out = __( \'No posts for this post type were found.\' );
endif;
if ( $fresh_terms ) {
foreach ( $fresh_terms as $term_id ) {
$term_data = get_term( $term_id );
$term_link = get_term_link( $term_id );
$out .= "$term_data->name";
}
}
return $out;
}
add_shortcode( \'fresh_categories\', \'display_terms_with_fresh_posts\' );
现在,您已经添加了显示“新类别”的快捷码,您可以在管理区域的页面中使用它,以您想要的方式打印类别:
[fresh_categories]
如果您想在php文件中使用它,只需执行以下操作:
echo do_shortcode("[fresh_categories]");
请注意我在代码片段中留下的注释。如果你想修改一下,它会对你有所帮助。