15

I've used a custom post type for one of my website. Custom post type contains scratch card data along with some custom fields.

I've developed an android application to manage those items from android device.

In the android app, I want to keep search feature which will help admin users to search card numbers to manage those.

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. But I need to retrieve all items with similar title.

Any suggestion?

1
  • Instead of using get_posts() you can use the default search query of WordPress which will provide you the results of the searched term. It will also provide all the matching results with all your search terms. Feb 11, 2013 at 10:44

3 Answers 3

32

You can use either search parameter of wp_query :

Code
$args = array("post_type" => "mytype", "s" => $title);
$query = get_posts( $args );

Or you can get posts based on title throught wpdb class:

global $wpdb;
$myposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_title LIKE '%s'", '%'. $wpdb->esc_like( $title ) .'%') );

Than you'll get post object in this form:

foreach ( $myposts as $mypost ) 
{
    $post = get_post( $mypost );
    //run your output code here
}
2
  • Is this working in 2019? Dec 12, 2019 at 18:58
  • 4
    Note that using s in get_posts will search more than just the title though... it also searches the content. Jul 11, 2020 at 15:48
11

Much simpler nowadays:

$posts = get_posts([
    'post_type'  => 'recipe',
    'title' => 'Chili Sin Carne',
]);

$posts will contain all recipes with the exact title "Chili Sin Carne".

3
  • OP was asking for a fuzzy match
    – alexg
    May 11, 2021 at 15:27
  • Oops, you're right. I only read the title :$
    – Jules
    May 15, 2021 at 10:18
  • thank you. it worked Dec 27, 2021 at 11:29
0

You can do something like this:

$posts = get_posts([
            'post_type'   => 'recipe',
            'post_status' => ['publish', 'draft', 'private'],
            's'           => 'search string',
            'search_columns' => ['post_title']
        ]);

This will search only the post_title of the posts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.