Queries and Custom Fields
-
So, I’m trying to get certain posts with a very specific set of requirements. I have several custom fields, for City, State, and Country, as well as a flag for having a post be highlighted, similar to a sticky post, but as a custom field.
EDIT: To clarify, the user has one location stored in $userLocation, so it needs to match either the City, the State, or the Country, it doesn’t matter what the meta_key is, only that the value matches. The highlighted key must exists and have a value of 1
At first I modified the query like so:
query_posts( array('post_type' => POST_TYPE, TAX_CAT => $term->slug, 'ignore_sticky_posts' => 1, 'posts_per_page' => 3, 'meta_query' => array ( 'relation' => 'AND', array ( 'key' => 'mpl_highlighted', 'value' => 1), array ( 'value' => $userlocation ) ), 'orderby' => 'rand' ) );
POST_TYPE, and TAX_CAT are because my posts are of a custom type and taxonomy. The problem with this is that it doesn’t seem to be matching the meta requirements with an AND. It’s getting all posts in the user’s location OR all posts with mpl_highlighted = 1, as far as I can tell. The results don’t seem to change if I use ‘relation’ => ‘OR’.
My next attempt was a custom SELECT query entirely:
<?php $postids = $wpdb->get_col( $wpdb->prepare( "SELECT key2.post_id FROM <code>wp_postmeta</code> key1 INNER JOIN <code>wp_postmeta</code> key2 ON key2.post_id = key1.post_id AND key1.meta_value = '". get_user_meta(get_current_user_id(), 'browse_loc', TRUE) ."' WHERE key2.meta_key = 'mpl_highlighted' AND key2.meta_value = 1 ORDER BY RAND() LIMIT 0, 3 ") ); ?>
The problem here being that all highlighted posts that match their location are returned regardless of their post or taxonomy.
Ideally, I’d like to use query_posts() but ensure I get the proper results. Could someone clarify to me how I’m using it incorrectly
- The topic ‘Queries and Custom Fields’ is closed to new replies.