• Resolved overwolf

    (@overwolf)


    How can i use get_posts() with multiple meta_key – meta_value agruments?

    $args = array(
       'numberposts' => 100,
       'meta_key'=>'category',
       'meta_value'=>'a',
       'meta_key'=>'color',
       'meta_value'=>'red'
     );
    get_posts($args);

    don’t works and uses only first meta

Viewing 4 replies - 1 through 4 (of 4 total)
  • You could code a custom query as shown here in the CODEX.

    Your SQL statement would be like this:

    $querystr = "
        SELECT wposts.*, meta1.meta_value as meta_value1, meta2.meta_value as meta_value2
        FROM $wpdb->posts wposts, $wpdb->postmeta meta1, $wpdb->postmeta meta2
        WHERE wposts.ID = meta1.post_id
        AND meta1.meta_key = 'category'
        AND meta1.meta_value = 'a'
        AND wposts.ID = meta2.post_id
        AND meta2.meta_key = 'color'
        AND meta2.meta_value = 'red'
        AND wposts.post_status = 'publish'
        AND wposts.post_type = 'post'
        ORDER BY wposts.post_date DESC
     ";

    Or, you could use the Query Multiple Taxonomies plugin.

    Scratch the plugin – its for categories and tags, not custom fields.

    Thread Starter overwolf

    (@overwolf)

    vtxyzzy, thanks a lot! I’ve tried to use custom query, but had problems with SQL.

    overwolf: Here’s the SQL that I am using to query for more than one custom field. Works great. Let me know if you think it works for you.

    $querydetails = "
    SELECT wposts.*
      FROM $wpdb->posts wposts
    INNER
      JOIN ( SELECT post_id
               FROM $wpdb->postmeta wpostmeta
              WHERE ( ( wpostmeta.meta_key = 'available'
                    AND wpostmeta.meta_value =  '$available' )
                   OR ( wpostmeta.meta_key = 'beds'
                    AND wpostmeta.meta_value $operator_beds '$beds' )
                   OR ( wpostmeta.meta_key = 'baths'
                    AND wpostmeta.meta_value = '$baths' )
                   OR ( wpostmeta.meta_key = 'type'
                    AND wpostmeta.meta_value = '$type' )
                   )
             GROUP
                 BY post_id
             HAVING COUNT(*) = 4 ) AS t
        ON t.post_id = wposts.ID
     WHERE wposts.post_status = 'publish'
       AND wposts.post_type = 'post'
    ORDER
        BY wposts.post_date DESC
     ";
    
    $pageposts = $wpdb->get_results($querydetails, OBJECT);

    The only problem I am having is that I cannot get pagination to work because of the custom query. Can anyone offer any help with that?

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Using get_posts with multiple meta values’ is closed to new replies.