Query for WooCommerce products by product specific custom attribute

// Set custom attribute name and value to search for
$attribute_name  = 'color';
$attribute_value = 'green';

$serialized_value = serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ); // extended version: $serialized_value = serialize( $attribute_name ) . 'a:6:{' . serialize( 'name' ) . serialize( $attribute_name ) . serialize( 'value' ) . serialize( $attribute_value ) . serialize( 'position' );
$args = array(
	'post_type'      => 'product',
	'post_status'    => 'any',
	'posts_per_page' => -1,
	'orderby'        => 'title',
	'order'          => 'ASC',
	'meta_query' => array(
		array(
			'key'     => '_product_attributes',
			'value'   => $serialized_value,
			'compare' => 'LIKE',
		),
	),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) {
	$loop->the_post();
	// do stuff here... e.g. get_the_ID()
}
wp_reset_postdata();

You can add this snippet to your (child) theme's functions.php file.

2 Comments

  1. Diljit Singh December 18, 2016 at 5:51 am #

    Ca you please add code for more than one attributes.

    • Adam D Boswell May 3, 2017 at 8:32 pm #

      I’m sure you’ve found this answer but for reference:
      to do multiple you have to decide if you’re going to use and AND or OR qualifier, then you can add multiple arrays:

      $args = array(
          'meta_query' => array(
              'relation' => 'OR',
              array(
                  'key'     => '_product_attributes',
                  'value'   => $serialized_value_1,
                  'compare' => 'LIKE',
              ),
              array(
                  'key'     => '_product_attributes',
                  'value'   => $serialized_value_2,
                  'compare' => 'LIKE',
              ),
          )
      );

Leave a Reply