rol*_*lex 6 php wordpress custom-post-type custom-taxonomy
我试图用一个计数器在作者页面中显示自定义分类,但似乎我不知道该怎么做.
我在function.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' );
}
});
Run Code Online (Sandbox Code Playgroud)
在我的作者页面中:
<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>
Run Code Online (Sandbox Code Playgroud)
该代码适用于所有作者配置文件,但我不知道如何使自定义分类法显示如下:
用户反馈
6积极反馈4负面反馈
所有反馈都在这里
所有反馈都在这里
所有反馈都在这里
顺便说一下,它是一个自定义的帖子类型(custom_feedback)和自定义分类法(feedback_taxonomy),有两个类别Positive和Negative.
请帮助大师?
实现这一点的唯一方法是运行两个单独的查询并计算从两个单独的查询返回的帖子。为此,我们将使用get_posts已经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';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |