woocommerce in wordpress return always simple as product type

泄露秘密 提交于 2019-12-10 21:52:08

问题


I try of get the type of a grouped product but woocommerce returns empty or always "simple" if I use WC_Product_Factory.

When I use:

$the_product = new WC_Product(2886);
echo $the_product->product_type;

returns empty.

When I use WC_Product_Factory:

$the_product = new WC_Product(2886);
$the_product_factory = new WC_Product_Factory();
$the_product = $the_product_factory->get_product($the_product);
echo $the_product->product_type;

always returns "simple"

I try to use:

$the_product = wc_get_product(2886);
echo $the_product->product_type;

but this returns an error "Call to a member function get_product() on a non-object in..."

My code is inside of:

add_action( 'plugins_loaded', function(){
    $the_product = new WC_Product(2886);
    echo $the_product->product_type;

    $the_product = new WC_Product(2886);
    $the_product_factory = new WC_Product_Factory();
    $the_product = $the_product_factory->get_product($the_product);
    echo $the_product->product_type;

    $the_product = wc_get_product(2886);
    echo $the_product->product_type;

    die();
});

Well, Thanks for your help!


回答1:


I found the solution or my mistake, change plugins_loaded to init:

add_action( 'init', function(){
    $the_product = new WC_Product(2886);
    echo $the_product->product_type;

    $the_product = new WC_Product(2886);
    $the_product_factory = new WC_Product_Factory();
    $the_product = $the_product_factory->get_product($the_product);
    echo $the_product->product_type;

    $the_product = wc_get_product(2886);
    echo $the_product->product_type;
    die();
});

and this work!

This url https://wordpress.stackexchange.com/questions/120055/woocommerce-create-new-product-and-add-to-cart-on-form-submit gave me the idea.

Happy coding! :)




回答2:


you can use this code to get the custom product type:

$terms = get_the_terms($product_id, 'product_type');
$product_type = !empty($terms) ? sanitize_title(current($terms)->name) : 'simple';


来源:https://stackoverflow.com/questions/28355770/woocommerce-in-wordpress-return-always-simple-as-product-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!