Support » Fixing WordPress » Get posts only if custom fields match

  • Resolved cmsnext

    (@cmsnext)


    I am trying to achieve this : I have 2 custom fields
    product_size
    product_color

    If I use

    $args = array(
    	'meta_key' => 'product_size',
    	'meta_value' => 'S',
            'post_type' => 'any'
    	);

    and if i use this

    $myposts = get_posts($args);

    I get all posts which have product_size as S.

    Secondly if I do

    $args = array(
    	'meta_key' => 'product_color',
    	'meta_value' => 'Blue',
            'post_type' => 'any'
    	);

    and if i use this

    $myposts = get_posts($args);

    I am able to get all posts with product color Blue.

    But when I use meta_query

    I am not able to do a query like…

    if product color = Blue and product size = S show posts…

    Thats not working. It always returns 0 value even though I manually checked and have posts wherein product size is S and product color is Blue. What is the query to be used to do AND query where in both conditions need to be fulfilled. i.e product color and product size

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    moderator

    Have you tried the parameter meta_query: http://codex.wordpress.org/Function_Reference/WP_Query#Custom_Field_Parameters

    something like this:

    $args = array(
    	'post_type' => 'product',
    	'meta_query' => array(
    		array(
    			'key' => 'product color',
    			'value' => 'Blue',
    			'compare' => '='
    		),
    		array(
    			'key' => 'product size',
    			'value' => 'S',
    			'compare' => '='
    		)
    	)
     );

    Hi keesiemeijer
    Thank you for the reply. Stand alone, yes that query works.

    But under loop its not working.

    What I mean is this.

    I m trying to create a list.

    Like

    Color & Size…
    Blue (4)
    – S (3)
    – M (1)

    Green (5)
    – XL (2)
    – S (2)
    – M (1)

    So when I run the above query under a loop for each color get size… this query fails.

    any idea to achive what I have mentioned above?

    I tried running the code in the loop but it displays total everywhere…

    eg.

    Blue (4)
    – XL (2)
    – S (5)
    – M (2)

    Green (5)
    – XL (2)
    – S (5)
    – M (2)

    Hence, its displaying all the items from the size category for both the colors. Its not using AND query but using OR query I searched a few forums… and there is an option
    compare => ‘AND’ but that does not seem to be working.

    Any ideas highly appreciated.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Get posts only if custom fields match’ is closed to new replies.