Quentin
Quentin

Reputation: 13

woocommerce how to get a product price with a shortcode

I'm trying to do a shortcode who will display the price of one product,

i just did that in my functions.php, it should be easy, did i miss something ?!

in my page i just put this shortcode : [product_price id="378"]

//shortcode woocommerce prix
function displayPriceProduct($item) {
   $productprice = wc_get_product($item)
    return $productprice->get_price();
}

add_shortcode('product_price', 'displayPriceProduct');

i just get a basic error without details, the page is not accessible anymore if i dont remove the code

Upvotes: 0

Views: 1762

Answers (1)

mahmood beheshti
mahmood beheshti

Reputation: 69

you can use this :

function displayPriceProduct( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
         $_product = wc_get_product( $atts['id'] );
         $html = "price = " . $_product->get_price();
    }
    return $html;
}
add_shortcode( 'woocommerce_product_price', 'displayPriceProduct' );

Your shortcode : [woocommerce_product_price id="99"]

also you can use below code for other price :

$_product->get_price();
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_date_on_sale_from();
$_product->get_date_on_sale_to();
$_product->get_total_sales();

or get product info :

$_product->get_type();
$_product->get_name();
$_product->get_slug();
$_product->get_date_created();
$_product->get_date_modified();
$_product->get_status();
$_product->get_featured();
$_product->get_catalog_visibility();
$_product->get_description();
$_product->get_short_description();
$_product->get_sku();
$_product->get_menu_order();
$_product->get_virtual();
get_permalink( $_product->get_id() );

or get product Dimensions :

$_product->get_weight();
$_product->get_length();
$_product->get_width();
$_product->get_height();
$_product->get_dimensions();

Get Product Images :

$_product->get_image_id();
$_product->get_image();
$_product->get_gallery_image_ids();

thanks

Upvotes: 1

Related Questions