Month: January 2017

Search in custom post type title and post meta using MySql query

Search in custom post type title and post meta using MySql query.

global $wpdb;
	$search_val = '';
	if(!empty($post['search_key'])){
		$search_val = '%' . mysql_real_escape_string($post['search_key']) . '%';
	}
	$query = "SELECT p1.ID FROM $wpdb->posts AS p1 ";
	$query .= " INNER JOIN $wpdb->postmeta AS p2 ON (p1.ID = p2.post_id) WHERE 1=1 ";
	
	if(!empty($search_val)){
		$query .= " AND ( (p1.post_title LIKE '$search_val')  ";
		$query .= " OR (p2.meta_key = 'people_title' AND CAST(p2.meta_value AS CHAR) LIKE '$search_val') ";
		$query .= " OR (p2.meta_key = 'office_location' AND CAST(p2.meta_value AS CHAR) LIKE '$search_val') ) ";
	}
	
	$query .= " AND p1.post_type = 'people'  ";
	$query .= " AND p1.post_status = 'publish' ";
	$query .= " GROUP BY p1.ID ORDER BY p1.menu_order ";	
Advertisements

Single qutes search In WordPress and PHP

In WordPress

$search = html_entity_decode($searchKey, ENT_QUOTES,  'UTF-8' );
	 
$args = array('post_status'=>"publish",'posts_per_page' => $limit,'offset' => $offset, 'order' => 'DESC' ,'s' => $search, 'post_type' => Array('post', 'page', 'markets' , 'people', 'post','projects','services') );

$result = new WP_Query( $args );

In PHP

$search_val = '';
if(!empty($post['search_key'])){
	$search_val = '%' . mysql_real_escape_string($post['search_key']) . '%';

$query = "SELECT p1.ID FROM $wpdb->posts AS p1 ";
$query .= " INNER JOIN $wpdb->postmeta AS p2 ON (p1.ID = p2.post_id) WHERE 1=1  (p1.post_title LIKE '$search_val')";
}