在 WooCommerce 中获取并显示选定的变体 SKU [英] Get and display the selected variation SKU in WooCommerce

查看:24
本文介绍了在 WooCommerce 中获取并显示选定的变体 SKU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码适用于简单的产品类型,但不适用于 WooCommerce 中的可变产品:

I have this code that works for simple product type but not for variable products in WooCommerce:

add_shortcode( 'product_sku_div', 'wc_product_sku_div'); 
function wc_product_sku_div() { 
    global $product;

    return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}

如何让它同时适用于简单产品和可变产品?

How can I make it work for both simple and variable products?

推荐答案

为了使其也适用于可变产品及其变体,它需要 Javascript (jQuery) 来获取可变产品的选定变体 SKU.

To make it work also for variable products and their variations, it requires Javascript (jQuery) to get the selected variation SKU for variable products.

尝试以下适用于简单可变产品类型的方法,显示可变产品的所选变体 SKU:

Try the following that works for simple an variable product types, displaying the selected variation SKU for variable products:

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    if( ! is_a('WC_Product', $product) ) {
        $product = wc_get_product( get_the_id() );
    }

    ## 1 - For variable products (and their variations)
    if( $product->is_type('variable') ) {
        ob_start(); // Starting buffering

        ?>
        <div class="widget" sp-sku=""></div>
        <script type="text/javascript">
        jQuery( function($){
            $('form.variations_form').on('show_variation', function( event, data ){
                $( 'div.widget' ).attr( 'sp-sku', data.sku );
                // For testing
                console.log( 'Variation Id: ' + data.variation_id + ' | Sku: ' + data.sku );
            });
            $('form.variations_form').on('hide_variation', function(){
                $( 'div.widget' ).attr( 'sp-sku', '' );
            });
        });
        </script><?php

        return ob_get_clean(); // return the buffered content
    }
    ## 2 - For other products types
    else {
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
    }
}

代码位于活动子主题(或活动主题)的 functions.php 文件中.经过测试和工作.

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

这篇关于在 WooCommerce 中获取并显示选定的变体 SKU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆