简体   繁体   中英

WooCommerce: Display product variations inside of loop

How can I display the product variations for each product within a loop such as the one on the Shop page? Is there any function that I can add to the content-product template that retrieves the list of variations and displays them?

You can use this code to add product variation to the shop/product category loops

 // Load our function when hook is set
add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query
function custom_modify_query_get_posts_by_date( $query ) {

    // Check if on frontend and main query is modified and if its shop or product category loop
    if( (! is_admin() && $query->is_main_query()) && ( is_shop() || is_product_category() ) ) {
        $query->set( 'order', 'ASC' );
        add_filter( 'posts_where', 'rc_filter_where' );
    }
    return $query;

}

// Add products variation post type to the loop
function rc_filter_where( $where = '' ) {

    $type = 'product_variation';
    $where .= " OR post_type = '$type'";

    return $where;

}

Best way to do this is alter the loop. Something like that will help:

   function filter_wc_query($query_args){
      if(is_archive()){ //here you can use any conditional function to show variations on 
        $query_args[] = ['post_parent'=> '*'];
      }
      return $query_args;
   }
   add_filter('woocommerce_get_query_vars','filter_wc_query');

Or if you want to this on view level: https://gist.github.com/lukecav/2470d9fe6337e13da4faae2f6d5fe15f

In this solution image you can grab by standard WP function:

get_post_thumbnail($product->ID,'shop_list');

But remeber that variation link will bring user to parent product and force him to select variation once more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM