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.
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.
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.
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.
[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.
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));
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With