Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

wordpress - PHP Script to force WooCommerce Variation

Hi I have a product store with 1000+ and have a problem with color/size variation pick. I used Variation Switch plugin to create custom bubbles under the product to show variation color on homepage or shop page, not only when customer enter the product. Then when user click on that color, site open that product and select the color but image of variation is not show until I select the correct size. I used this script to force select first variation :

<?php
add_action('woocommerce_before_single_product_summary', 'quadlayers_product_default_attributes');
function quadlayers_product_default_attributes() {
      global $product;
      if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) {
        $new_defaults = array();
        $product_attributes = $product->get_attributes();
        if (count($product_attributes)) {
          foreach ($product_attributes as $key => $attributes) {
            $values = explode(',', $product->get_attribute($key));
            if (isset($values[0]) && !isset($default_attributes[$key])) {
              $new_defaults[$key] = sanitize_key($values[0]);
            }
          }
          update_post_meta($product->get_id(), '_default_attributes', $new_defaults);
        }
      }
    }  
?>

and yes, it works but on some of the products which have first size variation in stock. If that variation is out of stock, it does nothing. Is it possible to customize this code to select first, second and third size variation which are in stock.

Little video for explain : https://www.loom.com/share/133cc60cd12342a8b605d3087a5048d6 (As you can see on first product, when I enter on color variation, it did not change image because there is no stock for 42+ size and it did not select anything so no change of image. But on second product, there is a stock for first variation and it's selected automatically and image is changed)

I found this script here : https://quadlayers.com/default-product-attributes-woocommerce/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...