【问题标题】:WordPress: Query Ordering by Parent TitleWordPress:按父标题查询排序
【发布时间】:2017-03-25 22:08:06
【问题描述】:

我正在处理我的主题中的一些自定义 WordPress 查询。它们都工作得很好,除了按帖子标题对它们进行排序之外,我需要按其父母的帖子标题的字母顺序对它们进行排序。

'orderby' 似乎没有默认参数来完成此操作,但我知道仍然必须有一种方法来完成它。

我的查询返回的所有帖子都是子帖子,因此它们都有一个父帖子。

仅供参考,这是一个显示我的格式的示例查询。也许我有一本 CPT“书”,每本书都有第 1 章、第 2 章等的帖子。如果我想列出每本书的所有“第 1 章”帖子,按书名字母顺序排序:

// List Chapter 1 for all Books

function query_ch1() {
  global $post;
  $args = array(
    'post_type'      => 'book',
    'name'           => 'chapter-1',
    'posts_per_page' => '-1',
    'order'          => 'ASC',
    'orderby'        => 'title'
  );
  $query_ch1 = new WP_Query( $args );
  if ( $query_ch1->have_posts() ) {
    while ( $query_ch1->have_posts() ) {
        $query_ch1->the_post();
        echo '<div class="col-xs-12">';
        echo '<a href="'.get_permalink().'" title="'.get_the_title().'">';
        echo get_the_title();
        echo '</a>';
        echo '</div>';
    }
    wp_reset_postdata();
  }
}

但是,这当然会按他们自己的帖子标题而不是他们父母的标题列出所有第 1 章的帖子。

任何帮助将不胜感激,在此先感谢!

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    这是你可以尝试的:

    • 使用get_posts($args) 之类的内容查询所有帖子。
    • 开始构建数组:$parents = [];
    • 遍历所有帖子并使用$parentTitle = get_the_title($post-&gt;post_parent) 之类的内容获取其标题。
    • 将帖子添加到他们的父母密钥$parents。比如:$parents[$parentTitle][] = $post;
    • 现在我认为您应该能够使用 ksort($parents); 根据键对 $parents 数组进行排序。

    现在您可以循环遍历$parents,然后循环遍历其posts:

    foreach ($parents as $posts) {
    
        foreach ($posts as $post)
            // Do stuff
        }
    
    }
    

    【讨论】:

    • 感谢您的帮助!我最终做了一些与您的处理方式有所不同的事情。
    【解决方案2】:

    我不确定这是否是理想的方法(就效率等而言),但经过大量试验后,我最终获得了预期的效果。

    使用我原始帖子中的示例,它将是:

    // List Chapter 1 for all Books
    
    function query_ch1() {
      global $post;
      $args = array(
        'post_type'      => 'book',
        'post_parent'    => '0',
        'posts_per_page' => '-1',
        'order'          => 'ASC',
        'orderby'        => 'title'
      );
      $query_ch1 = new WP_Query( $args );
      if ( $query_ch1->have_posts() ) {
        while ( $query_ch1->have_posts() ) {
          $query_ch1->the_post();
          $children = get_children( array( 'post_parent' => $post->ID, 'name' => 'chapter-1' ) );
          foreach ( $children as $post ) {
            echo '<div class="col-xs-12">';
            echo '<a href="'.get_permalink().'" title="'.get_the_title().'">';
            echo get_the_title();
            echo '</a>';
            echo '</div>';
          }
        }
        wp_reset_postdata();
      }
    }
    

    因此,在阅读了 Melvin Koopmans 的建议后,我将查询更改为拉顶级页面而不是子页面,以便正确排序它们,然后嵌套 get_children() 和 foreach($children as $post) 来做东西。

    【讨论】:

    • 是的,这是一个很好的解决方案。干得好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2020-12-18
    相关资源
    最近更新 更多