对@dgarceran的答案进行一点扩展
通常,使用WP_Query
类可能是查询帖子的好方法。
我们将要向该查询传递参数。
在您的情况下,我们可能需要使用以下选项之一:
- ”Custom Field Parameters“-
meta_query
- ”Taxonomy Parameters“-
tax_query
关于所有选项的一个近乎全面的示例,我想参考以下要点:
https://gist.github.com/luetkemj/2023628.
另请参见法典:https://codex.wordpress.org/Class_Reference/WP_Query
两者都采用关联数组,例如。
Note: 我将使用与PHP 5.4兼容的语法
$meta_query_args = [
[
\'key\' => \'season\',
\'value\' => [ \'2015\', \'2016\' ],
\'compare\' => \'IN\',
],
];
我们可以把这些论点带到
WP_Query
$args = [
\'post_type\' => \'player\',
\'posts_per_page\' => 100, // Set this to a reasonable limit
\'meta_query\' => $meta_query_args,
];
$the_query = new WP_Query( $args );
现在的情况是WordPress将检查所有与您的
custom post type player
. 然后,它将查询您用key设置的元数据
season
. 任何匹配的帖子
2015
或
2016
将返回。
Note: 使用meta_query
通常不建议使用这种方法,因为它对数据库的负担有点大。大家的共识似乎是,查询分类法的性能更高(不要引用我的话,找不到我的源代码)
因此,作为一个快速的替代方案,我推荐以下示例:
$tax_query_args = [
[
\'taxonomy\' => \'season\',
\'field\' => \'slug\',
\'terms\' => [ \'2015\', \'2016\' ],
\'operator\' => \'IN\',
],
];
$args = [
\'post_type\' => \'player\',
\'posts_per_page\' => 100, // Set this to a reasonable limit
\'tax_query\' => $tax_query_args,
];
$the_query = new WP_Query( $args );
现在我们可以实际循环数据了,下面是一些示例标记:
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, \'season\', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, \'season\', [ \'fields\' => \'names\' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( \'Season: \' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
当您使用
WP_Query
尤其是在模板中,请确保以
wp_reset_postdata();
总而言之(tl;dr)
$tax_query_args = [
[
\'taxonomy\' => \'season\',
\'field\' => \'slug\',
\'terms\' => [ \'2015\', \'2016\' ],
\'operator\' => \'IN\',
],
];
$args = [
\'post_type\' => \'player\',
\'posts_per_page\' => 100, // Set this to a reasonable limit
\'tax_query\' => $tax_query_args,
];
$the_query = new WP_Query( $args );
?>
<section class="season-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$post_id = get_the_ID();
// $season = get_post_meta( $post_id, \'season\', true ); // example if you are still going to use post meta
$season = wp_get_object_terms( $post_id, \'season\', [ \'fields\' => \'names\' ] );
?>
<h3><?php the_title(); ?></h3>
<p><?php echo __( \'Season: \' ) . sanitize_text_field( implode( $season ) ); ?></p>
<?php endwhile; ?>
</section>
<?php
wp_reset_postdata();
Front-end view of our query:Dashboard view of CPT Player posts:希望能提供一点背景