结合使用WP_Query和自定义SQL?

时间:2019-10-20 11:19:48

标签: php mysql sql wordpress

我要使用此SQL。

"ORDER BY CASE WHEN post_title >= 'C' THEN 1 ELSE 0 END DESC, post_title ASC".

此SQL排序过帐并返回以字母“ C”开头的过帐。我想按首字母排序来搜索帖子。这段SQL代码是我的决定。

  • 我尝试使用过滤器“ posts_orderby”添加这部分SQL。但这行不通。
  • 我尝试$ wpq = new WP_Query($ query);
$sql = "SELECT post_title FROM `baddoc_posts` WHERE post_title LIKE '%Иван%' AND post_type = 'doctor' ORDER BY CASE WHEN post_title >= 'И' THEN 1 ELSE 0 END DESC, post_title ASC";
$wpq = new WP_Query();
$wpq->parse_query($sql);
$wpq->get_posts();
function wpse_298888_posts_where( $where, $query ) {
    global $wpdb;

    $starts_with = $query->get( 'starts_with' );

    if ( $starts_with ) {
        $where .= " ORDER BY CASE WHEN $wpdb->posts.post_title >= '$starts_with' THEN 1 ELSE 0 END DESC, $wpdb->posts.post_title ASC";
    }

    return $where;
}
add_filter( 'posts_orderby', 'wpse_298888_posts_where', 10, 2 );

1 个答案:

答案 0 :(得分:0)

function wpse_postorderby( $orderby, $query ) {
    global $wpdb;

    $starts_with = $query->get( 'starts_with' );

    if ( $starts_with ) {
        $orderby = "CASE WHEN post_title >= '$starts_with' THEN 1 ELSE 0 END DESC, post_title ASC";
    }

    return $orderby;
}
add_filter( 'posts_orderby', 'wpse_postorderby', 10, 2 );

我解决了!只需删除“。”之前=