【问题标题】:Add a new product type in Woocommerce 3在 Woocommerce 3 中添加新产品类型
【发布时间】:2018-03-17 13:20:18
【问题描述】:

在 Woocommerce 中,我创建了一个自定义产品类型 live_stream

但是,当我在此自定义类型中创建新产品并发布它时,该产品仍然是“简单产品”,并且没有为其设置 live_stream 自定义类型。

我做错了什么?如何使该自定义产品类型发挥作用?

这是我的代码

function wpstream_register_live_stream_product_type() {
    class Wpstream_Product_Live_Stream extends WC_Product {
        public function __construct( $product ) {

            $this->product_type = 'live_stream';
            parent::__construct( $product );

        }

        public function get_type() {
            return 'live_stream';
        }
    }
}

add_action( 'init', 'wpstream_register_live_stream_product_type' );

function wpstream_add_products( $types ){
    $types[ 'live_stream' ]             = __( 'Live Channel','wpestream' );
    return $types;
}
add_filter( 'product_type_selector', 'wpstream_add_products' );

【问题讨论】:

    标签: php wordpress class woocommerce product


    【解决方案1】:

    由于 Woocommerce 3 $this->product_type = 'live_stream'; 已被弃用并且在构造函数中不需要。必须通过在此自定义产品类型的 Class 中的构造函数之外定义函数 get_type() 来替换它。

    所以你的代码将是:

    add_action( 'init', 'new_custom_product_type' );
    function new_custom_product_type(){
        class WC_Product_Live_Stream extends WC_Product{
    
            public function __construct( $product ) {
                parent::__construct( $product );
            }
    
            // Needed since Woocommerce version 3
            public function get_type() {
                return 'live_stream';
            }
        }
    }
    
    add_filter( 'product_type_selector', 'custom_product_type_to_type_selector' );
    function custom_product_type_to_type_selector( $types ){
        $types[ 'live_stream' ] = __( 'Live Channel', 'wpestream' );
        return $types;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    这应该可以解决您的问题。

    【讨论】:

    • 嗨,@LoicTheAztec,我正在尝试使用命名空间在 PSR4 中编写插件代码,如何在函数内创建 r 调用类?
    • @MilindSingh 我对 PSR4 一无所知,所以应该在 StackOverFlow 中询问您的问题,例如:“如何在函数内部的 PHP 类中创建 r 调用”(但不是专门针对 Woocommerce 或 wordpress)……
    猜你喜欢
    • 1970-01-01
    • 2022-11-05
    • 2022-09-25
    • 2020-11-28
    • 2018-12-10
    • 2017-06-26
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多