使自定义帖子类型按字母顺序正确显示

时间:2015-06-22 作者:Tiger Danky

我试图让自定义帖子类型的子循环按字母顺序显示,但没有成功。我尝试将ksort和asort应用于$posts 数组,但它只是对ID显示重新排序,而不是对标题进行排序。

enter image description here

    // alphabetical menu: https://wordpress.stackexchange.com/questions/119163/displaying-custom-post-type-by-first-letter-through-custom-taxonomy
    // get all totems
    $args = array(
       \'post_type\' => \'totem\',
       \'posts_per_page\' => -1
    );
    $query = new WP_Query($args);

    // order by first letter of each totem
    $by_letter = array();
    while( $query->have_posts() ) { $query->the_post();
      global $post;
      $letter = substr($post->post_name, 0, 1);
      if ( ! isset($by_letter[$letter]) ) $by_letter[$letter] = array();
      $by_letter[$letter][] = $post;
    }
    wp_reset_postdata();

    // order the array
    ksort($by_letter);

    // fill the array with letters that have no posts
    $by_letter = fill_by_letter_array( $by_letter );

    ?>

    <div class="totem-zoo-alphabet-mobile">
        <ul>
            <?php foreach( $by_letter as $letter => $posts ) {
                    ?>
                    <li class="<?php echo (empty($posts) ? \'empty\':\'\') ?>">
                        <?php echo $letter; ?>
                        <?php if ( ! empty($posts)): ?>
                            <ul>
                                <?php   
                                    ksort($posts); // ATTEMPTING TO SORT POSTS BY TITLE... FAIL
                                    foreach ( $posts as $post ) {
                                    setup_postdata($post);
                                    echo \'<li><a href="\' . get_permalink() . \'">\'. get_the_title() . \'</a></li>\';
                                } ?>
                            </ul>
                        <?php endif;?>
                    </li>
                  <?php
                  }
                  wp_reset_postdata();
            ?>
        </ul>
    </div>

Functions used from here

1 个回复
最合适的回答,由SO网友:Sladix 整理而成

正如ChrisL在评论中所说,您应该在参数中添加order和orderby:

 $args = array(
       \'post_type\' => \'totem\',
       \'posts_per_page\' => -1,
       \'orderby\' => \'title\',
       \'order\' => \'ASC\'
    );

结束

相关推荐

如何使用WP_QUERY排除特定标记?

我有以下用于查询特定类别和标记slug的工作代码:$args = array( \'category_name\' => $cat_name, \'tag\' => $tag_name, \'post__not_in\' => $sticky ); $my_query = new WP_Query( $args ); 我不知道如何从查询中排除特定的标记名。我需要标签ID吗?我怎么得到它?提前谢谢你。