Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I need to select posts who are in multiple categories and have certain post metavalue. I can select multiple categories with

query_posts( array( 'category__and' => array(1,2,3) ) );

But also I need from those selected categories, select only those posts who have certain meta_value from wp_postmeta table. This task I can do with sql query:

SELECT DISTINCT (
p.ID
), p . *
FROM wp_posts AS p
INNER JOIN wp_postmeta AS p1 ON ( p.ID = p1.post_id )
CROSS JOIN wp_postmeta AS p3
USING ( post_id )
WHERE p3.meta_key = 'length'
AND convert( p3.meta_value, signed )
BETWEEN '".$min_length."'
AND '".$max_length."'
AND post_status = 'publish'
$subSelect
ORDER BY p.ID DESC

I don't understand how can I select for example only those posts who has category 1 AND 2 AND 3 AND postmeta meta_key length is BETWEEN $min_length AND $max_length?

share|improve this question
add comment

1 Answer

Since version 3.1 WP got much enhanced querying of custom fields. If I got the code right your query should be something like this:

query_posts(array(
    'category__and' => array(1,2,3),
    'meta_query' => array(
        array(
            'key' => 'length',
            'value' => array($min_length, $max_length),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC',
        ),
    ),
));

See:

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.