在 WooCommerce 中获取并显示选定的变体 SKU

编程入门 行业动态 更新时间:2024-10-26 20:34:14
本文介绍了在 WooCommerce 中获取并显示选定的变体 SKU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有这段代码适用于简单的产品类型,但不适用于 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-25 06:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080004.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变体   WooCommerce   SKU

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!