sgb004
sgb004

Reputation: 357

woocommerce in wordpress return always simple as product type

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!

Upvotes: 6

Views: 2992

Answers (2)

Ahmad Yazji
Ahmad Yazji

Reputation: 566

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

Upvotes: 2

sgb004
sgb004

Reputation: 357

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! :)

Upvotes: 5

Related Questions