From 15996a1dee4370202fa86e2900b37207be18e360 Mon Sep 17 00:00:00 2001 From: claudiosmweb Date: Thu, 27 Nov 2014 10:31:56 -0200 Subject: [PATCH] Created the wc_get_product_id_by_sku() function --- includes/class-wc-shortcodes.php | 4 ++-- includes/wc-product-functions.php | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/includes/class-wc-shortcodes.php b/includes/class-wc-shortcodes.php index e311645af22..8b01ea1a55a 100644 --- a/includes/class-wc-shortcodes.php +++ b/includes/class-wc-shortcodes.php @@ -500,7 +500,7 @@ class WC_Shortcodes { if ( ! empty( $atts['id'] ) ) { $product_data = get_post( $atts['id'] ); } elseif ( ! empty( $atts['sku'] ) ) { - $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $atts['sku'] ) ); + $product_id = wc_get_product_id_by_sku( $atts['sku'] ); $product_data = get_post( $product_id ); } else { return ''; @@ -546,7 +546,7 @@ class WC_Shortcodes { if ( isset( $atts['id'] ) ) { $product_data = get_post( $atts['id'] ); } elseif ( isset( $atts['sku'] ) ) { - $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $atts['sku'] ) ); + $product_id = wc_get_product_id_by_sku( $atts['sku'] ); $product_data = get_post( $product_id ); } else { return ''; diff --git a/includes/wc-product-functions.php b/includes/wc-product-functions.php index ba6dffcd84e..8d39ad6f773 100644 --- a/includes/wc-product-functions.php +++ b/includes/wc-product-functions.php @@ -523,3 +523,18 @@ function wc_product_has_unique_sku( $product_id, $sku ) { return true; } } + +/** + * Get product ID by SKU. + * + * @since 2.3.0 + * @param string $sku + * @return int + */ +function wc_get_product_id_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 ) ); + + return ( $product_id ) ? intval( $product_id ) : 0; +}