Reputation: 1359
In Woocommerce, I have created a custom product type live_stream
.
But when I create a new product within this custom type and I publish it, the product remains a "simple product" and doesn't get the live_stream
custom type set for it.
What I am doing wrong? How to make that custom product type functional?
Here is my code
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' );
Upvotes: 2
Views: 1012
Reputation: 960
I was debugging this as well. I use namespaces, so I was considering that this is part of the problem. It is not. So for future (and other people's) reference.
The class lookup happens in wp-content/plugins/woocommerce/includes/class-wc-product-factory.php
:
/**
* Create a WC coding standards compliant class name e.g. WC_Product_Type_Class instead of WC_Product_type-class.
*
* @param string $product_type Product type.
* @return string|false
*/
public static function get_classname_from_product_type( $product_type ) {
return $product_type ? 'WC_Product_' . implode( '_', array_map( 'ucfirst', explode( '-', $product_type ) ) ) : false;
}
You can use this snippet (or set a breakpoint on debugging) to determine why your $product-type
does not resolve to the correct classname.
In my case I had a product name like my_class
and thought mistakenly it would resolve to My_Class
, which it does not, it resolves to My_class
.
Upvotes: 0
Reputation: 253901
Since Woocommerce 3 $this->product_type = 'live_stream';
is deprecated and not needed in the constructor. It has to be replaced by defining the function get_type()
outside the constructor in the Class for this custom product type.
So your code will be:
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;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
This should solve your issue.
Upvotes: 2