Wordpress 循环:自定义字段值“yes”> 按分类法“a”排序,自定义字段值“no”> 按分类法“b”排序

问题描述 投票:0回答:1

尝试搜索和测试了两天,但似乎没有让这个循环按照我想要的方式工作。任何帮助将不胜感激。

  1. 我想循环浏览自定义帖子类型(我知道如何做到这一点)
  2. 在此循环中,我首先想列出一些具有自定义字段值(“是”)的帖子(数量可能会有所不同),然后根据分类值(长度)对这些帖子进行排序。
  3. 然后我想列出其余的帖子(这些帖子有一个自定义字段值“否”)并根据分类值(年份)对这些帖子进行排序。

这些页面使用分页。我尝试了两个不同的循环,但由于第一部分是未定义数量的帖子,这对我不起作用。最重要的是,如果可能的话,它在一个循环中感觉“更干净”。

到目前为止,这就是我所拥有的:

<?php $args = array(
   'post_type' => 'custom-post-type-name',
   'posts_per_page' => 24,
   'paged' => $paged,
   'meta_query' => array(
      'first-posts' => array(
         'meta_key' => 'highlighted-post',
         'meta_value' => 'yes',
       ),
      'other-posts' => array(
         'meta_key' => 'highlighted-post',
         'meta_value' => 'no'
      ), 
   ),
   'orderby' => array(
      'first-posts' => 'ASC',
      'other-posts' => 'DESC'
   ),
); ?>
php wordpress loops taxonomy custom-fields
1个回答
0
投票

您必须提出两个查询,一个针对“是”的帖子,另一个针对“否”的帖子。另外,调用元查询时您的查询是错误的。

我们设置分页:

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

“是”的帖子:

<?php $yes_posts = get_posts(array(
   'post_type' => 'custom-post-type-name',
   'posts_per_page' => 24,
   'paged' => $paged,
   'meta_query' => array(
     array(
         'meta_key' => 'highlighted-post',
         'meta_value' => 'yes',
       ),
   ),
   'order' => 'ASC'
)); ?>

“不”帖子:

<?php $no_posts = get_posts(array(
   'post_type' => 'custom-post-type-name',
   'posts_per_page' => 24,
   'paged' => $paged,
   'meta_query' => array(
      array(
         'meta_key' => 'highlighted-post',
         'meta_value' => 'no'
      ), 
   ),
   'orderby' => 'DESC'
)); ?>

我们组合查询来获取最后一个查询的帖子 ID 列表:

$allposts = array_merge($yes_posts, $no_posts);
$postids = array();
foreach( $allposts as $item ) {
    $postids[] = $item->ID;
}

我们创建一个帖子 ID 数组

$unique = array_unique($postids);
$args = array(
    'post__in' => $unique,
    'paged' => $paged,
    'orderby' => 'post__in'
);

我们进行循环:

$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) {
    $checking = 0;
    while ( $the_query->have_posts() ) { $the_query->the_post();
        // Handle posts here
    }
    wp_reset_postdata();
}

将页面中的所有代码组合起来,它应该可以工作。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.