Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress get_posts by title like

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.

like image 359
Nico Martin Avatar asked Aug 03 '14 10:08

Nico Martin


People also ask

How to search by post title in WordPress?

I can use wordpress query to search by title. Code $args = array ("post_type" => "mytype", "name" => $title); $query = get_posts ( $args ); It can only provide result if I provide exact title.

What is the use of get_posts in WordPress?

The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching this criteria. get_posts can also be used to create Multiple Loops, though a more direct reference to WP_Query using new WP_Query is preferred in this case.

Does search for Hello parameter work with the post title?

While adding your search term into the s parameter work and it will search the post title, it will also search the post content. What about the title parameter which was added with WP 4.4? Is case sensitive and LIKE, not %LIKE%. This mean search for hello will not return post with title Hello World or Hello. Show activity on this post.

How do I show only the most recent posts for each category?

[ACT-list show=”Category” postspercategory=”20″] will show only the 20 most recent posts for each category. By default, the posts will be listed from newest to oldest. To change this behaviour, use the reverse-date=1 parameter.


2 Answers

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

$quote_ids = array_column($results, 'ID');

$quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));
like image 149
Bullyen Avatar answered Sep 19 '22 13:09

Bullyen


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
}   
like image 28
Tomás Cot Avatar answered Sep 17 '22 13:09

Tomás Cot