Using custom fields with wp_query
-
Hi, i’m new to this plugin and i think it’s amazing. Makes my life easier.
I’m trying to get some posts using a custom field as a filter for the query. I’m trying to use the field as part of the meta_query but it seems it doesn’t filter anything.
This is my code:
$query_args = array( 'post_type' => 'recipe' , 'meta_query' => array( 'key' => 'ingredients' , 'value' => "%ingredient1%" , 'compare' => 'LIKE' ) ); $query = new WP_Query( $query_args );Can anyone help me? Thanks!
http://ww.wp.xz.cn/extend/plugins/custom-content-type-manager/
-
Warning: my response is biased because I hate WP_Query with a passion. I wrote the GetPostsQuery class specifically to combat what I felt were incomplete and ineffective “solutions” offered in the WordPress core and the insane way they are continuously molested by an over-reliance on events and hooks.
So my recommendation is to use GetPostsQuery: https://code.google.com/p/wordpress-custom-content-type-manager/wiki/GetPostsQuery or the SummarizePosts shortcode that implements it. See https://code.google.com/p/wordpress-custom-content-type-manager/wiki/get_posts_examples for examples.
So if I rewrote your above arguments, the code in your template file might look something like this:
$Q = new GetPostsQuery(); $args = array(); $args['post_type'] = 'recipe'; $args['ingredients']['like'] = 'sugar'; // Set the the 2nd argument argument to "true" to force results to include // unpublished or otherwise non-standard results $results = $Q->get_posts($args); foreach ($results as $r) { // print stuff here }Note that if you are filtering on repeatable fields, your queries become more difficult because the data are stored inside a JSON array. It’s just one of those tradeoffs.
Hi, fireproofsocks:
Thanks for your quick answer. I’m going to make more complicated my question.
What if I have more than one ingredient and I want a recipe which has one of those ingredients at least? In other words, how I combine several ‘like’ queries:
$Q = new GetPostsQuery(); $args = array(); $args['post_type'] = 'recipe'; $args['ingredients']['like'] = 'sugar'; $args['ingredients']['like'] = 'honey'; $args['ingredients']['like'] = 'chocolate'; $args['ingredients']['like'] = 'strawberries'; // Set the the 2nd argument argument to "true" to force results to include // unpublished or otherwise non-standard results $results = $Q->get_posts($args); foreach ($results as $r) { // print stuff here }That’s trickier. It should be supported, but there are a couple glitches for me to work out.
I know! Please, when you have this part worked out, tell me here. Thanks for everything.
Please subscribe to the relevant bug in the bug-tracker: I don’t police the forums.
Ok. Thanks, I’m going to subscribe now.
The topic ‘Using custom fields with wp_query’ is closed to new replies.