简体   繁体   English

按自定义值字段分组的WordPress帖子

[英]Group by a custom value field wordpress posts

I have several posts with a custom field named "series". 我有几篇自定义字段为“ series”的帖子。 I want to group all posts by this custom field and below of this i want to list all posts which have not this custom field. 我想按此自定义字段对所有帖子进行分组,在此下方,我要列出没有此自定义字段的所有帖子。

First i wanted to get grouped custom field value and then to be able to query again for all posts with this custom value key and value. 首先,我想获得分组的自定义字段值,然后能够再次使用此自定义值键和值查询所有帖子。 But even trying to get the unique custom values does not work. 但是,即使尝试获取唯一的自定义值也不起作用。

What i tried is this: 我试过的是:

<?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>

Whats wrong with this code? 此代码有什么问题?

WP_Meta_Query WP_Meta_Query

All posts with custom value: 具有自定义值的所有帖子:

<?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; ?>

And without values: 没有值:

<?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; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM