订购自定义帖子类型

时间:2015-05-19 08:27:54

标签: wordpress custom-post-type

我正在注册一个新的自定义帖子类型:

function news_register() {
    $labels = array(
        'name' => _x('News', 'post type general name'),
        'singular_name' => _x('News Item', 'post type singular name'),
        'add_new' => _x('Add New News Article', 'resources item'),
        'add_new_item' => __('Add New News Article'),
        'edit_item' => __('Edit News Article'),
        'new_item' => __('New News Article'),
        'view_item' => __('View News Article'),
        'search_items' => __('Search News Articles'),
        'not_found' =>  __('Nothing found'),
        'not_found_in_trash' => __('Nothing found in Trash'),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 8,
        'supports' => array('title','editor', 'excerpt', 'thumbnail', 'excerpt')
    ); 
    register_post_type( 'news' , $args );
}
add_action('init', 'news_register');

然后我尝试查询这些帖子类型,并使用以下标题按标题排序:

$news = new WP_Query(array(
      'post_type'  => 'news',
      'orderby'    => 'name',
      'order'      => 'DESC'
  ));

或者:

$args = array( 'post_type' => 'news', 'posts_per_page'=>5, 'orderby'=>'title','order'=>'ASC');
$news = new WP_Query( $args );

根据帖子标题的顺序都没有。新闻帖子是名为'aaa','bbb'和'ccc。

的测试文章

如何更改查询以按标题顺序获取帖子?

编辑:

我在函数中有这个代码,但删除它似乎没有改变任何东西。

add_filter('pre_get_posts','change_my_post_order');

function change_my_post_order( $query ) {
    global $wp_query;

    if ( is_category() ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'asc' );
    }

    return $query;
}

向查询添加“'suppress_filters'=> true,”似乎也没有任何区别。

1 个答案:

答案 0 :(得分:0)

您的pre_get_posts操作错误。您应该确保只定位前端而只定位主查询。你的行动应该是这样的

add_action( 'pre_get_posts','change_my_post_order' );

function change_my_post_order( $query ) {

    if ( !is_admin() && $query->is_main_query() && $query->is_category() ) {
        $query->set( 'orderby', 'title' );
        $query->set( 'order', 'asc' );
    }
}