woocommerce in wordpress return always simple as p

2019-07-21 10:37发布

问题:

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';