Query for WooCommerce products by global product attributes

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

$args = array(
	'post_type'      => 'product',
	'post_status'    => 'any',
	'posts_per_page' => -1,
	'orderby'        => 'title',
	'order'          => 'ASC',
	'tax_query'      => array(
		array(
			'taxonomy' => 'pa_' . $attribute_name,
			'field'    => 'name', // can be 'slug'
			'terms'    => $attribute_value,
		),
	),
);
$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.

No comments yet.

Leave a Reply