WP_Custom帖子类型一一查询

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

我有两种帖子类型。

<?php  
$args = [ 
         'post_type' => ['type1', 'type2'], 
         'orderby' => ['type' => 'ASC']
        ];

$query = new WP_Query($args); ?>

因此,我需要显示type1帖子,并在其下方显示type2帖子。我的代码以随机顺序显示它们。我的错误在哪里?

wordpress custom-post-type
3个回答
0
投票

您必须在文件内部使用此文件,并使用$query来遍历项目:

if ($query->have_posts()): 
   while ($query->have_posts()): $query->the_post()
   //the rest of the loop here

如果无法在模板中添加此查询,则需要使用过滤器来拦截查询:

add_filter( 'posts_orderby' , 'order_by_type_func' );
function order_by_type_func( $orderby ) {
    global $wpdb;
    $table = $wpdb->prefix.'posts';

    if(!is_admin()){
        $orderby = $table.".post_type ASC"; 
    }
    return $orderby;
}

然后按照您的意愿运行常规查询。


0
投票

[我认为您应该在参数的“ post_type”行中使用一个数组,对于一般的参数,请使用圆括号(而不是方括号),并在orderbyorder的不同行中保持如下所示:] >

$args = array( 
  'post_type' => array('type1', 'type2'), 
  'orderby' => 'type',
  'order' => 'ASC',
);

0
投票

有一种使用post对象执行此操作的简单方法,因此您可以将项目准确放置在所需的位置。像这样:

© www.soinside.com 2019 - 2024. All rights reserved.