这是我在 function.php
中编写的代码:
add_action('transition_post_status', 'send_new_post', 9876543210, 3);
function send_new_post($new_status, $old_status, $post) {
if('publish' === $new_status && 'publish' !== $old_status && $post->post_type === 'product') {
global $wpdb;
$current_product_id = $post->ID;
if(isset($current_product_id)) {
$post_id = $current_product_id;
} else {
$post_id = '131';
}
$sql = "SELECT
post_id as id,
(SELECT post_title FROM wp_posts WHERE id = pm.post_id) AS title,
(SELECT post_name FROM wp_posts WHERE id = pm.post_id) AS name,
(SELECT meta_value FROM wp_postmeta WHERE post_id = pm.post_id AND meta_key = '_price' LIMIT 1) AS price,
(SELECT meta_value FROM wp_postmeta WHERE post_id = pm.post_id AND meta_key = '_regular_price' LIMIT 1) AS 'regular_price',
(SELECT meta_value FROM wp_postmeta WHERE post_id = pm.post_id AND meta_key = '_stock' LIMIT 1) AS stock,
IFNULL((SELECT meta_value FROM wp_postmeta WHERE post_id = pm.post_id AND meta_key = '_sku' LIMIT 1),
(SELECT meta_value FROM wp_postmeta WHERE post_id = pm.post_id AND meta_key = '_custom_field' LIMIT 1)) as sku
FROM `wp_postmeta` AS pm
JOIN wp_posts AS p ON p.ID = pm.post_id
WHERE p.ID = ".$post_id." AND meta_key in ('_product_version')
AND p.post_status in ('publish')";
$results = $wpdb->get_results($sql);
$result = json_decode(json_encode($results), true);
$data_init = $result[0];
$tablename=$wpdb->prefix.'product_init';
$data=array(
'post_id' => $data_init['id'],
'post_title' => $data_init['title'],
'post_name' => $data_init['name'],
'price' => $data_init['price'],
'regular_price' => $data_init['regular_price'],
'sku' => $data_init['sku'],
'stock' => $data_init['stock'],
'created_by' => 'Created By Custom Code'
);
$wpdb->insert( $tablename, $data);
}
}
当我添加产品时,我得到以下结果,其中缺少一些值。
我不明白为什么我没有得到其他值(价格、regular_price、sku 和 stock)。 我怎样才能得到这些?
答案 0 :(得分:0)
我不建议在 WooCommerce 产品 API 之外使用自定义查询和更新元数据,因为查看 WooCommerce 尝试优化数据库的更改,并且您的代码将在某些更新后停止工作。使用 WC_Product class 中方法的最佳且更简单的方法。
$product = wc_get_product( $post->ID );
$product->set_sku( 'qwe-123' );
$product->set_stock_quantity( 15 );
$product->set_regular_price( 123 )
$product->set_price( 123 );
$product->save();