【问题标题】:How to order posts list using wp_query?如何使用 wp_query 排序帖子列表?
【发布时间】:2018-07-12 01:29:35
【问题描述】:

我想用 wp_query 订购我的清单。我有带有 meta_key 'featured_post' 的帖子和该键的三个值,用于不同的帖子:'1'、'2' 和第三个键不存在。

我现在正在使用这个 wp_query 结构:

global $paged, $wp_query, $wp;
$args = wp_parse_args($wp->matched_query);
if ( !empty ( $args['paged'] ) && 0 == $paged ) {
    $wp_query->set('paged', $args['paged']);
    $paged = $args['paged'];
}
$temp = $wp_query;
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 20,
    'paged' => $paged,
    'meta_query' => array(
        'relation' => 'OR',
        'featured_clause_first' => array(
            'key' => 'featured_post',
            'value' => '1',
            'compare' => '='
        ),
        'featured_clause_second' => array(
            'key' => 'featured_post',
            'value' => '2',
            'compare' => '='
        ),
        'featured_clause_third' => array(
            'key' => 'featured_post',
            'compare' => 'NOT EXISTS',
            'value' => '1'
        )
    ),
    'orderby' => array( 
        'featured_clause_first' => 'DESC',
        'featured_clause_second' => 'DESC',
        'featured_clause_third' => 'DESC'
    ),

);
$wp_query = null;
$wp_query = new WP_Query($args);
while ($wp_query->have_posts()) : $wp_query->the_post();
    get_template_part( 'templates/single');
endwhile;
wp_reset_postdata();
wp_reset_query();

但是我的顺序有误。最后,我需要在顶部查看值为 '1' 的帖子和其他值为 '2' 且之后不存在键的帖子。

注意:我不能使用“'meta_key' => 'featured_post'”,因为这样不会显示没有现有 meta_key 的帖子。

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    好的。如果未选中功能,我编辑了用于删除元键的保存元框功能。所以我只有两个值:1 & key 不存在。之后我得到了这个元参数所需的订单:

    $sort_meta_query = array(
        'relation' => 'OR',
        'featured_clause' => array(
            'key' => 'featured_post',
            'value' => '1',
            'compare' => '='
        ),
        array(
            'key' => 'featured_post',
            'compare' => 'NOT EXISTS',
            'value' => '1'
        )
    );
    $sort = array(
        'orderby' => array(
            'featured_clause' => 'DESC',
            'date' => 'DESC'
        )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      相关资源
      最近更新 更多