WooCommerce - Get the product description by product_id
Asked Answered
M

3

13

How can I get the product description or the product object using product ID.

$order = new WC_Order($order_id);

foreach ($order->get_items() as $item) {
    $product_description = get_the_product_description($item['product_id']); // is there any method can I use to fetch the product description?
}

The code above extends class WC_Payment_Gateway

Any help would be greatly appreciated.

Morehouse answered 4/11, 2013 at 8:22 Comment(1)
Hint: If your description is written in post content, use Vincent's answer; if your description is written in WooCommerce's product description field, use Raunak's answer.Christhood
M
20
$order = new WC_Order($order_id);

foreach ($order->get_items() as $item)
{
    $product_description = get_post($item['product_id'])->post_content; // I used wordpress built-in functions to get the product object 
}
Morehouse answered 14/11, 2013 at 6:46 Comment(0)
A
13

If you are using WooCommerce 3.0 or above, then you can get description with the below code.

$order = wc_get_order($order_id);

foreach ($order->get_items() as $item) {
    $product_id = $item['product_id'];
    $product_details = $product->get_data();

    $product_full_description = $product_details['description'];
    $product_short_description = $product_details['short_description'];
}

Alternate way (recommended)

$order = wc_get_order($order_id);

foreach ($order->get_items() as $item) {
    $product_id = $item['product_id'];
    $product_instance = wc_get_product($product_id);

    $product_full_description = $product_instance->get_description();
    $product_short_description = $product_instance->get_short_description();
}

Hope this helps!

Angelita answered 2/7, 2017 at 7:9 Comment(1)
I think, there is one line missing like $product = new WC_Product($product_id); I would also suggest to use the specific methods to ensure the hooks are executed: $product_full_description = $product->get_description(); $product_short_description = $product->get_short_description();Arlindaarline
P
1
<?php echo wc_get_product( $post->ID )->get_short_description(); ?>
Particiaparticipant answered 4/5, 2023 at 15:59 Comment(2)
Code-only answers aren't ideal. Could you add some context explaining what this code does and how it addresses OP's problem?Seeing
This answer is perfect, the context is in the title of the original question.Otilia

© 2022 - 2024 — McMap. All rights reserved.