Query WooCommerce Products based on Attribute. If product attribute is saved as specific product attribute (i.e. not global), then you can’t query it as taxonomy, instead you can use the below snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // 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(); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.