wordpress WP_Query类的“ orderby”或“ order”参数的条件

时间:2019-02-02 06:56:42

标签: php ajax wordpress

上下文:在Wordpress中使用Ajax。

functions.php

       $filterby = $_POST['filter'];
        $orderby = $_POST['order'];
        $args = array(
            'post_type' => 'projects',
            'posts_per_page' => -1,
            // 'orderby' => $orderby,
            'orderby' => array( 'title' => 'ASC', 'date' => 'DESC' ),
            // 'order' => 'ASC',
            'category_name' => $filterby,
        );

$filterby关注帖子类别。

$orderby可以是'date''title',具体取决于用户选择的内容。

如果它是'date',我要“ order” =>“ DESC”。 [首先显示最新帖子]

如果它是'title',我要“ order” =>“ ASC”。 [按字母顺序显示,从a到z]

感谢您抽出宝贵的时间。

2 个答案:

答案 0 :(得分:1)

简单地使用如果语句检查

$filterby = $_POST['filter'];
$orderby = $_POST['order'];
$args = [
    'post_type' => 'projects',
    'posts_per_page' => -1,
    'category_name' => $filterby
];
if($orderby == 'date'){
    $args['orderby'] = 'date'; 
    $args['order'] = 'DESC';
}elseif($orderby == 'title'){
    $args['orderby'] = 'title';
    $args['order'] = 'ASC';
}else{
    unset($args['order']); unset($args['orderby']);
}

$query = new WP_Query($args);

答案 1 :(得分:0)

    $date_args = array(
        'post_type' => 'projects',
        'posts_per_page' => -1,
        'orderby' => $orderby,
        'order' => 'DESC',
        'category_name' => $filterby,
    );
    $title_args = array(
        'post_type' => 'projects',
        'posts_per_page' => -1,
        'orderby' => $orderby,
        'order' => 'ASC',
        'category_name' => $filterby,
    );

 if ( $_POST['order'] == date ) {
    $the_query = new WP_Query( $date_args );
 } elseif ( $_POST['order'] == title ) {
        $the_query = new WP_Query( $title_args );
        }