为什么search_columns参数不适用于WordPress中的get_posts()函数?

2q5ifsrm  于 5个月前  发布在  WordPress
关注(0)|答案(1)|浏览(78)

我写了一个插件,需要搜索一个关键字后标题。
根据get_posts()的文档,我应该能够通过将“search_columns”参数设置为“post_title”来将搜索限制为文章标题。不幸的是,这没有做任何事情。结果仍然包含关键字出现在文章标题或内容中的文章。
我做错了什么吗?或者这是WordPress的问题?
我使用的只是vanilla WordPress v5.9.2。我的代码:

function search_posts($keyword, $params) {

    $args = array(
        'post_type'   => $params['type'],
        'post_status' => array('publish', 'draft', 'pending', 'future'),
        'numberposts' => 10,
        'search_columns' => array('post_title'),
        's'           => $keyword,
    );

    $matching_posts = get_posts($args);

    return $matching_posts;
}

字符串

beq87vna

beq87vna1#

在WordPress 5.9.2中,get_posts()WP_Query中没有内置参数来限制搜索仅限于使用search_columns的帖子标题。要解决此限制,您可以通过WordPress的$wpdb类使用自定义SQL查询。

function search_posts_by_title($keyword, $post_type = 'post') {
    global $wpdb;

    $keyword = '%' . $wpdb->esc_like($keyword) . '%';

    $sql = $wpdb->prepare(
        "SELECT * FROM {$wpdb->posts} WHERE post_title LIKE %s AND post_type = %s AND post_status IN ('publish', 'draft', 'pending', 'future')",
        $keyword,
        $post_type
    );

    $posts = $wpdb->get_results($sql);

    return $posts;
}

字符串

相关问题