Jenny, first of all, I think you may be better off using Taxonomy Parameters in you queries. However, there are a couple of hackish ways to do what you want to some extent.
$my_query = new WP_Query( 'post_type=post&posts_per_page=-1' );
$posts = $my_query->get_posts();
foreach ( $posts as &$post ) {
// Get the details and unset if thy type is unwanted
$details = get_post_meta( $post->ID, 'details', true );
if ( isset($details['type'])
and $details['type'] != 'my_type ')
unset( $post );
}
This will filter out posts that don’t match a type
of my_type
in your details
meta for the post.
However, note the performance issue – get_post_meta
is called for each and every post, resulting in queries to the database. Ouch!
There is a more complex way to do this using a custom query to get all the meta at once like so:
$sql = "SELECT `post_id`, `meta_value`".
" FROM {$wpdb->postmeta}".
" WHERE `meta_key` = 'details'";
// Gather my meta
$metas = $wpdb->get_results( $sql );
$details = array();
foreach ( $metas as $meta ) $details[$meta->post_id] = unserialize($meta->meta_value);
$my_query = new WP_Query( 'post_type=post&posts_per_page=-1' );
$posts = $my_query->get_posts();
foreach ( $posts as &$post ) {
// Filter the unwanted posts
if ( isset($details[$post->ID]['type'])
and $details[$post->ID]['type'] != 'my_type' )
unset( $post );
}
This way you did only one extra query, by bringing the meta in in the beginning. A couple of things to note here:
- the basic principal is there – get all the posts, and filter them by
unset
ting - $wpdb` should be in scope (if you’re inside a function or method bring it in as a global)
- if you’re going to play around with
" WHERE meta_key = 'details'";
make sure you escape what you feed into the query, otherwise it will be at risk of SQL injection - wrap these into functions that will allow you to reuse them
- if you have a lot of posts in the query, this can get slow