wordpress - ordering multiples post types

老子叫甜甜 提交于 2020-01-24 20:30:11

问题


i'm trying to order multiples post types in a page my solution below is working but the posts are not showing by type after type exactly

                <?php $args = array_merge( $wp_query->query,
                array( 'post_type' =>array( 'editorial','video','portfolio' ),'posts_per_page=-1','orderby'=>'post_type') );
                }
                query_posts( $args );

                $postType='';

                 if (have_posts()) : while (have_posts()) : the_post();
                 $PT = get_post_type( $post->ID );
                if($postType != $PT){
                 $postType =  $PT;
                echo '<p class="clearfix"><h1>All posts of type : '.$postType.'</h1></p>';
                }   
                ?>  

      <?php
      if($postType == 'editorial'){ ?>
          <?php echo $postType; ?>
          <?php }elseif($postType == 'video'){ ?>
          <?php echo $postType; ?>
          <?php }elseif($postType == 'portfolio'){ 
          <?php echo $postType; ?>
          }
          ?>

and it output like that:

All posts of type : editorial

editorial

editorial

editorial

All posts of type : video

video

video

All posts of type : editorial //problem

editorial

All posts of type : portfolio

portfolio

portfolio

portfolio

portfolio

thank you in advance


回答1:


According to the Codex, post_type isn't one of the allowed values for the orderby parameter.

One way around your problem would be to use the posts_orderby filter, something like this:

function order_posts_by_type($original_orderby_statement) {
    global $wpdb;
    return $wpdb->posts .".post_type ASC";
}

add_filter('posts_orderby', 'order_posts_by_type');

$custom_query = new WP_Query( array(
    'post_type' =>array( 'editorial','video','portfolio' ),
    'posts_per_page' => '-1',
    'orderby'=>'post_type',
    'order' => 'ASC'
) );

remove_filter('posts_orderby', 'order_posts_by_type');

FWIW, I'd suggest changing 'posts_per_page=-1' to 'posts_per_page' => -1 to be consistent with your other arguments.



来源:https://stackoverflow.com/questions/11275574/wordpress-ordering-multiples-post-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!