我有一个自定义的帖子类型,有一个与之关联的自定义字段。我已经设置了一个WP\\u查询来返回该帖子类型的所有帖子。我想做的是显示第一个满足自定义字段唯一条件的字段,而不是任何后续字段。
例如,假设我有5篇文章,对于这5篇文章,自定义字段(称为“大小”)填写如下:
帖子1-字段值:小帖子2-字段值:中帖子3-字段值:小帖子4-字段值:大帖子5-字段值:中帖子我希望查询在到达重复字段值时自动检测到的内容,因此返回帖子列表如下:
有人有什么想法吗?
我有一个自定义的帖子类型,有一个与之关联的自定义字段。我已经设置了一个WP\\u查询来返回该帖子类型的所有帖子。我想做的是显示第一个满足自定义字段唯一条件的字段,而不是任何后续字段。
例如,假设我有5篇文章,对于这5篇文章,自定义字段(称为“大小”)填写如下:
帖子1-字段值:小帖子2-字段值:中帖子3-字段值:小帖子4-字段值:大帖子5-字段值:中帖子我希望查询在到达重复字段值时自动检测到的内容,因此返回帖子列表如下:
有人有什么想法吗?
基于这些评论,我想我应该在查询本身之外实现这一点,并使用PHP过滤结果。我也会给你第二个解决方案,但我认为第一个更容易理解(稍后再讨论)。
由于我不知道您的代码的细节,这里有一种伪代码方法。
$unique_fields_array = array();
// you loop will contain all custom post types regardless of custom field values
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
// get the custom field for this specific post
$meta_value = get_post_meta( $the_query->post->ID, \'size\', true );
// if we\'ve never output a post with this custom field value yet, do it now, and then add it to the unique_fields_array
if ( !in_array($meta_value, $unique_fields_array) ) {
// OUTPUT YOUR POST CONTENT HERE
$unique_fields_array[] = $meta_value;
}
}
}
// restore original postdata
wp_reset_postdata();
第二种解决方案是将WP\\u查询全部绕过(我不建议这样做,但这里还是这样)。global $wpdb;
$values = $wpdb->get_results("SELECT DISTINCT meta_value FROM $wpdb->postmeta pm, $wpdb->post p WHERE meta_key = \'size\' and pm.post_id=p.ID and p.post_type=\'my_custom_postype\' ", ARRAY_A);
然后可以循环$values
在PHP中,它们将只包含大小唯一的记录。当然,您可以使用排序、附加过滤器等自定义此SQL。这更多的是在基本PHP领域,而WP的循环“魔术”常常忽略了这一点。
$values = array();
while( have_posts() ) : the_post();
if ( in_array( $something, $values ) {
continue; // we already saw this kind of something, skip the post
} else {
$values[] = $something; // seeing it for the first time, let\'s remember that
}
// usual loop stuff
endwhile;
嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post