23
votes

I want to be able to display a product title by using PHP to echo the product name by the product ID (this is to be displayed within a Page, not the product page itself). I am using Wordpress and I have a plugin for PHP so I can include PHP code using [php]echo 'example';[/php]

One product example is; http://ukcctvinstallations.co.uk/product/1-camera-residential-system-hi-res/

When I edit the product, you can see in the URL that the 'Post' = 129 so am I right in saying this is the product ID?

If anyone has a solution for this, that would be much appreciated. I am using WooCommerce.

3

3 Answers

49
votes

Assuming you get the product as an object

$product = wc_get_product( id );

echo $product->get_title();

(WC version 2.5.2)

24
votes
7
votes

2017 - 2020 - Since WooCommerce 3, use the WC_Product method get_name()

global $product;

// If the WC_product Object is not defined globally
if ( ! is_a( $product, 'WC_Product' ) ) {
    $product = wc_get_product( get_the_id() );
}

echo $product->get_name();

On cart items:

foreach( WC()->cart->get_cart() as $cart_item ) {
    echo $cart_item['data']->get_name();
}

On Order items:

foreach( $order->get_items() as $cart_item ) {
    echo $item->get_name();
    // Or
    $product = $item->get_product(); // Get the WC_Product Object
    echo $product->get_name();
}