【问题标题】:Using WP_Query with custom SQL?将 WP_Query 与自定义 SQL 一起使用?
【发布时间】:2019-10-20 11:19:48
【问题描述】:

我想使用这个 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 );

【问题讨论】:

    标签: php mysql sql wordpress


    【解决方案1】:
    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 );
    

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

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 2017-07-04
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多