我正在尝试使用计数器在作者页面中显示自定义分类,但似乎我不知道该怎么做。
我有一个代码函数.php
add_action( 'pre_get_posts', function ( $q ) {
if( !is_admin() && $q->is_main_query() && $q->is_author() ) {
$q->set( 'posts_per_page', 100 );
$q->set( 'post_type', 'custom_feedback' );
}
});
在我的作者页面中:
<div class="feedback-respond">
<h3 class="feedback-title">User Feedback </h3>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: ?>
<p><?php _e('No posts by this author.'); ?></p>
<?php endif; ?>
</div>
该代码适用于所有作者个人资料,但我不知道如何让自定义分类显示如下:
用户反馈
6 正面反馈 4 负面反馈
所有反馈都在这里
所有反馈都在这里
所有反馈都在这里
顺便说一下,它是一个自定义帖子类型(custom_feedback)和自定义分类法(feedback_taxonomy),有两个类别“正面”和“负面”。
请高手帮忙?
实现这一点的唯一方法是运行两个单独的查询并计算从两个单独的查询返回的帖子。为此我们将使用get_posts
as get_posts
已经将一些重要的默认值传递给WP_Query
使查询更快、更注重性能。
我们将为查询添加一个巨大的时间和资源节省器,'fields' => 'ids'
。它的作用是,它只获取帖子 ID,而不是完整的帖子对象。这可以将查询时间和数据库查询减少 99%,因此即使您要在整个数据库上运行 2 个单独的查询,页面性能的损失也不会明显。
让我们将所有内容放入代码中(这进入author.php,注意,此代码未经测试,至少需要 PHP 5.4+)
$author_id = get_queried_object_id(); // Gets the author id when viewing the author page
// Add our term slugs into an array.
$terms = ['positive', 'negative']; // Just make sure these values are correct
$count = [];
foreach ( $terms as $term ) {
// Build our query
$args = [
'nopaging' => true,
'post_type' => 'custom_feedback',
'author' => $author_id,
'tax_query' => [
[
'taxonomy' => 'feedback_taxonomy',
'field' => 'slug',
'terms' => $term
],
],
'fields' => 'ids'
];
$q = get_posts( $args );
// Count the amount of posts and add in array
$count[$term] = count( $q );
}
// Display our text with post counts, just make sure your array keys correspond with your term slugs used
$positive = ( isset( $count['positive'] ) ) ? $count['positive'] : 0;
$negative =( isset( $count['negative'] ) ) ? $count['negative'] : 0;
echo $positive . ' POSITIVE feedback ' . $negative . ' NEGATIVE feedback';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)