WordPress get_posts by title like

无人久伴 提交于 2019-12-07 14:10:21

问题


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

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

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.


回答1:


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
}   



回答2:


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));



回答3:


Or you could use the filter posts_where like this:

$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;
}


来源:https://stackoverflow.com/questions/25103949/wordpress-get-posts-by-title-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!