WordPress get_posts by title like

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25103949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:59:09  来源:igfitidea点击:

WordPress get_posts by title like

wordpressgettitleposts

提问by Nico Martin

I am trying to create a small search-function for WordPress. An AJAX call should get all posts where the title is like %quote%.

我正在尝试为 WordPress 创建一个小的搜索功能。AJAX 调用应该获取标题为%quote%.

Is there a possibility to make this happen inside the get_posts()function?

是否有可能在get_posts()函数内部实现这一点?

Don't get me wrong. The ajax works fine. I have the ajax function in my functions.php and I receive the posts. It's just the "where title like" part where I couldn't find a solution.

不要误会我的意思。ajax 工作正常。我的functions.php 中有ajax 函数,我收到了这些帖子。这只是我找不到解决方案的“标题喜欢”部分。

回答by Bullyen

You could do a custom search query also.

您也可以进行自定义搜索查询。

$search_query = "SELECT ID FROM {$wpdb->prefix}posts
                         WHERE post_type = "post" 
                         AND post_title LIKE %s";

$like = '%'.quote.'%';
$results = $wpdb->get_results($wpdb->prepare($search_query, $like), ARRAY_N);
foreach($results as $key => $array){
     $quote_ids[] = $array['ID'];
}

$quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));

回答by Tomás Cot

No, but you can create a custom loop.

不,但您可以创建自定义循环。

Check this.

检查这个。

EDIT:

编辑:

$args = array('s' => 'keyword');

$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {

    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        //whatever you want to do with each post
    }
} else {
     // no posts found
}   

回答by Mike

Or you could use the filter posts_wherelike this:

或者你可以posts_where像这样使用过滤器:

$options = array(
    'posts_per_page' => -1,
    'suppress_filters' => false, // important!
    'post_type' => 'post',
    'post_status' => 'publish',
);
$keyword = 'quote';

add_filter( 'posts_where', 'my_filter_post_where' );
$posts = get_posts( $options );
remove_filter( 'posts_where', 'my_filter_post_where' );

function my_filter_post_where( $where) {
    global $wpdb;
    global $keyword;

    $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $keyword ) ) . '%\'';

    return $where;
}