Woocommerce使用产品SKU获取产品ID [英] Woocommerce get Product id using product SKU

查看:364
本文介绍了Woocommerce使用产品SKU获取产品ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个单独的模板页面上,该页面使用wordpress post的自定义字段获取woocommece产品sku.我需要获取该sku的产品ID以创建woocommece对象并执行其他操作,这是我的代码.

I'm working on a separate templates page, which page gets woocommece product sku using custom field of wordpress post. i need to get product id of that sku for create woocommece object and do further things, here is my code.

global $woocommerce;
//this return sku (custom field on a wordpress post)
$sku=get_field( "product_sku" );
if($sku!=''){
  //need to create object, but using sku cannot create a object, 
  $product = new WC_Product($sku); 
  echo $product->get_price_html();
}

是否可以在创建对象之前获取产品ID,然后可以将产品ID传递给WC_Product类构造函数并创建对象.谢谢

is there way to get product id before create object, then i can pass the product id to WC_Product class constructor and create object.thank you

推荐答案

您可以使用此功能(在此处找到). Google是您的朋友!

You can use this function (found here). Google is your friend!

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;
}

这篇关于Woocommerce使用产品SKU获取产品ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆