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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
}
Method 2
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”.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0