• I’m trying to take two meta_vales and filter by both.

    Example.
    If this page has meta values red and blue, only display pages that have both red and blue and none that have just red or just blue.

    I thought this could be accomplished with two meta values 'meta_value' => $red, $blue but apparently it’s not available. Below is where I found myself before the block. Any help would be appreciated.

    <?php
    		$red = get_post_meta($post->ID, 'red', true);
    		$blue = get_post_meta($post->ID, 'blue', true);
    		$args = array(
    		'post_type' => page,
    		'nopaging' => true,
    		'post_parent' => 1440,
    		'meta_value' => $red, $blue
    		);
        ?>
      <?php query_posts($args);?>
Viewing 1 replies (of 1 total)
  • The code below shows how to use filters to select on two meta_values. However, I am not sure it will do what you actually want.

    Because you are using get_post_meta to get the values for $red and $blue, it will select any post that has a meta_key of ‘red’ AND a meta_key of ‘blue’ regardless of the meta_values for those keys.

    Give it a try and it can be refined if it is not exactly right.

    <?php function mam_posts_join ($join) {
       global $mam_global_join;
       if ($mam_global_join) $join .= " $mam_global_join";
       return $join;
    }
    function mam_posts_where ($where) {
       global $mam_global_where;
       if ($mam_global_where) $where .= " $mam_global_where";
       return $where;
    }
    add_filter('posts_join','mam_posts_join');
    add_filter('posts_where','mam_posts_where');
    
    $red = get_post_meta($post->ID, 'red', true);
    $blue = get_post_meta($post->ID, 'blue', true);
    $mam_global_join =
    "JOIN $wpdb->postmeta pm1 ON ($wpdb->posts.ID = pm1.post_id)
    JOIN $wpdb->postmeta pm2 ON ($wpdb->posts.ID = pm2.post_id)";
    $mam_global_where =
       " AND pm1.meta_key = 'red' AND pm1.meta_value ='$red'
       AND pm2.meta_key = 'blue' AND pm2.meta_value ='$blue'";
    $args = array(
       'post_type' => page,
       'nopaging' => true,
       'post_parent' => 1440,
       'meta_value' => $red, $blue
    );
    
    query_posts($args);
    $mam_global_join = $mam_global_where = ''; // Turn off filters
    ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Filtering with multiple meta_values’ is closed to new replies.