I think the problem essentially relates to sql query structure and I am not an expert....
I need to search for posts (custom post type) by 2 parameters:
pd_city
pd_country
Please note that meta_query relation is 'OR' so if either of above two is LIKE we should have some results.
Third key (is_sponsored) is used to sort posts! It can be 1 or 0 and posts whose "is_sponsored" value equals to 1 should be listed on top.
So here's the WordPress thing:
$sfp_query_args = array(
'sfp_complex_search' => 'yeap',
'tax_query' => array( array( 'taxonomy' => 'sfp_post_category', 'terms' => $term_id ) ),
//'meta_key' => 'is_sponsored',
'post_type' => 'sfpposts',
'post_status' => 'publish',
'showposts' => (int)$per_page,
'paged' => $paged,
'meta_query' => array( 'relation' => 'OR',
array( 'key' => 'pd_city', 'value' => $sfp_search_meta, 'compare' => 'LIKE' ),
array( 'key' => 'pd_country', 'value' => $sfp_search_meta, 'compare' => 'LIKE' ),
array( 'key' => 'is_sponsored' )
)
);
$sfp_search = new WP_Query( $sfp_query_args );
I also need to filter results with "posts_orderby" in order to get those sponsored to the top:
add_filter( 'posts_orderby', 'sfp_modify_search' );
function sfp_modify_search( $orderby ) {
if( !is_admin() && is_page( $this->options[ 'sfp_page_entries_search' ] ) ) {
global $wpdb;
$orderby = " CASE WHEN mt2.meta_value = 0 THEN 1 END, $wpdb->posts.post_date DESC ";
}
return $orderby;
}
The real problem relies in fact that with this query ALL POSTS from "sfp_post_category" are returned, not only those who match "pd_city" or "pd_country" because ALL POSTS HAVE "is_sponsored" meta key (and value set to 1 or 0). Once again: "is_sponsored" is needed for sorting!
When var_dump
var_dump( $sfp_search->request );
...WordPress' sql looks like this:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (77) )
AND wp_posts.post_type = 'sfpposts'
AND (wp_posts.post_status = 'publish')
AND ( (wp_postmeta.meta_key = 'pd_city'
AND CAST(wp_postmeta.meta_value AS CHAR)
LIKE '%something%')
OR (mt1.meta_key = 'pd_country'
AND CAST(mt1.meta_value AS CHAR)
LIKE '%something%')
OR mt2.meta_key = 'is_sponsored' )
GROUP BY wp_posts.ID
ORDER BY CASE WHEN mt2.meta_value = 0 THEN 1 END, wp_posts.post_date DESC
LIMIT 0, 10
How do I eliminate all posts that do not match "pd_city" or "pd_country" from results?