我有几个帖子,其中包含一个名为“series”的自定义字段。我想按照此自定义字段对所有帖子进行分组,在此下面我要列出所有没有此自定义字段的帖子。
首先,我希望获得自定义字段值的分组,然后能够再次查询具有此自定义值键和值的所有帖子。但即使尝试获取独特的自定义值也无效。
我试过的是这个:
<?php
function query_group_by_filter($groupby){
global $wpdb;
return $wpdb->postmeta . '.meta_key = "series"';
}
?>
<?php add_filter('posts_groupby', 'query_group_by_filter'); ?>
<?php $states = new WP_Query(array(
'meta_key' => 'series',
'ignore_sticky_posts' => 1
));
?>
<?php remove_filter('posts_groupby', 'query_group_by_filter'); ?>
<ul>
<?php
while ( $states->have_posts() ) : $states->the_post();
$mykey_values = get_post_custom_values( 'series' );
foreach ( $mykey_values as $key => $value ) {
echo "<li>$key => $value ( 'series' )</li>";
}
endwhile;
?>
</ul>
这段代码有什么问题?
答案 0 :(得分:1)
所有具有自定义值的帖子:
<?php
$args = array(
'post_type' => 'my-post-type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'series',
'value' => 'my-val',
'compare' => '='
),
array(
'key' => 'series',
'value' => '',
'compare' => '!='
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
endwhile;
wp_reset_postdata(); ?>
</ul>
<?php endif; ?>
没有价值观:
<?php
$args = array(
'post_type' => 'my-post-type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'series',
'value' => '',
'compare' => '='
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
endwhile;
wp_reset_postdata(); ?>
</ul>
<?php endif; ?>