Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

wordpress - How do I get upsell for variable product in Woocommerce?

Short version: How do I get upsell for variable product in Woocommerce?

Longer version: I need the product ids for upsells. My old code contains depracated code:

$upsells = $product->get_upsells(); // $product is instace of WC_Product_Variable::

The call should be the following:

$upsells = $product->get_upsells_ids(); // $product is  WC_Product::

But a different class.

I tried to get the parent instance using wc_get_product($product->get_parent_id()) - but fail.

So, given the instance of WC_Product_Variable how do I get to the parent method WC_Product::$product->get_upsells_ids() ??

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The get_upsells-ids() method does not exist.

Try get_upsell_ids().

More information here: https://woocommerce.github.io/code-reference/classes/WC-Product.html#method_get_upsell_ids

The following code will show you all the upsell ids for the product you are currently visiting:

// quick test to check upsell ids 
add_action( 'woocommerce_before_single_product', 'echo_upsell_ids' );
function echo_upsell_ids() {
    global $product;
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
    $product = wc_get_product( $product_id );
    $upsell_ids = $product->get_upsell_ids();
    echo '<pre>' . print_r( $upsell_ids, true ) . '</pre>';
}

I have tested the code and it works. The snippet goes into your child theme's functions.php file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...