I need to display the price of a given product by using sku , trying to do it with few shortcodes i have found but not much luck - would like to view the price on the page after entering a product's sku into the shortcode, like this [woocommerce_price sku="sku123"] [woocommerce_price sku="sku345"]
anyone would be able to advise how to achieve that?
see here for an example code i tried but doesnt work
extract( shortcode_atts( array(
'sku' => null,
), $atts, 'woocommerce_price' ) );
if( intval( $sku ) > 0 && function_exists( 'wc_get_product' ) ){
$product = wc_get_product_id_by_sku( $sku );
if ( $product->get_price() > 0 ) {
return $product->get_price_html();
} else {
return __( "Price unavailable", "woocommerce" );
}
}
}
add_shortcode( 'woocommerce_price', 'wc_price_shortcode_callback' );```
CodePudding user response:
You can use this function and get price
function get_product_by_sku( $sku ) {
global $wpdb;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id ) return new WC_Product( $product_id );
return null;}
$product = get_product_by_sku( $sku);
$product->get_regular_price();
$product->get_sale_price();
$product->get_price();
CodePudding user response:
This should be the inner shortcode code after your extract.
if( !is_null($sku) && function_exists( 'wc_get_product' ) ){
$product_id = wc_get_product_id_by_sku( $sku );
$product = wc_get_product($product_id); //get the product object from id here.
if ( $product->get_price() > 0 ) {
return $product->get_price_html();
} else {
return __( "Price unavailable", "woocommerce" );
}
}