I have a custom post type set up with Advanced Custom Fields. I would like to display and order my posts in groups. The groups are states of the United States, so I have 50 groups.
Should I perform one query per state or is there a way to create one query that will cycle through all the different ( key : value ) (states) values and echo them out to the page in their respective groups?
<?php
$posts = get_posts(array(
\'posts_per_page\' => -1,
\'post_type\' => \'school\',
\'meta_key\' => \'state\',
\'meta_value\' => \'Texas\'
));
if( $posts ): ?>
<?php foreach( $posts as $post ): setup_postdata( $post ) ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
This is the standard ACF query by meta value.
SO网友:jdm2112
一种选择是将所有帖子提取到单个数组中,并对该数组进行50次过滤。这将只生成一个查询:
$posts = get_posts(array(
\'posts_per_page\' => -1,
\'post_type\' => \'school\'
));
要过滤阵列,请执行以下操作:
$this_state = "Texas";
$state_posts = array_filter($posts, function($results) use($this_state) {
return $results[\'state\'] == $this_state;
});
从那里开始,
$state_posts
应包含
$posts
德克萨斯州所在地。为50个组中的每个组进行适当修改。
这是未经测试的,但以我上周编写的非常类似的模板为模型。