【问题标题】:How to add Variations tab in custom product type in Woocommerce?如何在 Woocommerce 的自定义产品类型中添加变体选项卡?
【发布时间】:2017-03-16 13:33:41
【问题描述】:
  • 我已经为“礼品卡”安装了一个插件,它基本上是添加一个 产品类型“礼品卡”。
    • 我需要增强它的功能。
    • 还有其他可用的选项卡,但选项卡“变体”是 不是。
    • 如何添加此选项卡,以便我的自定义产品类型也可以 表现得像一个可变产品。
    • 截图:http://prntscr.com/ekogwd
    • 而且我必须严格使用我的自定义产品类型,这意味着我不能将其更改为可变产品类型。
    • 是否有任何挂钩、操作或过滤器可以使用 woocommerce 将此选项卡手动添加到我的自定义产品类型“礼品卡”中?

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce


    【解决方案1】:

    我假设您已经将礼品卡添加到产品类型选择器中。但是,我在这里添加它是为了完整性,因为您必须在第二个函数中使用相同的名称。

    add_filter( 'product_type_selector', 'so_42835590_add_product_type' );
    function so_42835590_add_product_type( $types ){
    
        // Key should be exactly the same as in the class product_type parameter
        $types[ 'gift-card' ] = __( 'Gift Card', 'your-plugin' );
    
        return $types;
    
    }
    

    您可以通过过滤woocommerce_product_data_tabs 添加自己的自定义选项卡,但您也可以向现有选项卡添加类。类是元框 javascript 用来决定在产品类型更改时显示和隐藏的内容。

    add_filter( 'woocommerce_product_data_tabs', 'so_42835590_product_data_tabs' );
    function so_42835590_product_data_tabs( $tabs ) {
    
        $product_type = 'gift-card'; // must match array key in previous snippet
    
        // Add an additional class to an existing tab, ex: Variations.
        $tabs[ 'variations' ][ 'class' ][] = 'show_if_' . $product_type;  
    
        return $tabs;
    }
    

    编辑您确实需要添加一些 javascript 来控制现有属性中“启用变体”选项卡的可见性以及添加属性的时间。这应该可以解决问题:

    jQuery( function ( $ ) {
    
        // Variable type options are valid for variable workshop.
        $( '.show_if_variable:not(.hide_if_gift-card)' ).addClass( 'show_if_gift-card' );
    
        // Trigger change
        $( 'select#product-type' ).change();
    
        // Show variable type options when new attribute is added.
        $( document.body ).on( 'woocommerce_added_attribute', function(e) {
    
            $( '#product_attributes .show_if_variable:not(.hide_if_gift-card)' ).addClass( 'show_if_gift-card' );
    
            var $attributes     = $( '#product_attributes' ).find( '.woocommerce_attribute' );
    
            if ( 'gift-card' == $( 'select#product-type' ).val() ) {
                $attributes.find( '.enable_variation' ).show();
            }
        });
    
    });
    

    【讨论】:

    • 感谢@helgatheviking 它有效。您能否添加更多详细信息,如何在属性选项卡中显示复选框字段“用于变体”? prntscr.com/el16t1 这仅在产品类型为可变产品时显示。
    • 查看我添加的脚本。
    • 非常感谢@helgatheviking
    • 我按照这里的指南进行操作,它似乎工作正常,除了当我选择可变产品类型时“变体”选项卡现在被隐藏了。我该怎么办?
    • @Ethan 应该由过滤 woocommerce_product_data_tabs 的第二个 sn-p 处理。我对其进行了调整,使其更具可读性...gift-card 需要替换为您的产品类型,并且需要与所有 sn-ps 匹配。
    猜你喜欢
    • 2021-07-24
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2021-06-28
    相关资源
    最近更新 更多