【问题标题】:Group by a custom value field wordpress posts按自定义值字段分组 wordpress 帖子
【发布时间】:2017-12-26 10:10:50
【问题描述】:

我有几个帖子,其中包含一个名为“系列”的自定义字段。我想按此自定义字段对所有帖子进行分组,在此下方我想列出所有没有此自定义字段的帖子。

首先,我想获得分组的自定义字段值,然后能够再次查询具有此自定义值键和值的所有帖子。但即使尝试获取唯一的自定义值也行不通。

我尝试的是这样的:

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

这段代码有什么问题?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    WP_Meta_Query

    所有具有自定义值的帖子:

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

    【讨论】:

    • 谢谢!但是第一部分(带有值的查询)不是我直接搜索的。我首先需要按自定义字段分组。例如,按自定义字段“系列”分组,假设我发布了值为“开发系列”和“云系列”的帖子,然后我想按这两个变量自定义字段值分组,然后在这些组下方显示相关帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2015-10-01
    相关资源
    最近更新 更多