I want to store stock quantity of product & its variations along with Product_id(Post ID) in a custom table after the creation of a new product. for this i am using ‘transition_post_status’ hook & for reading the stock value i am using wp_postmeta table $prodcut_qty = get_post_meta($post->ID,'_stock');
.
Suppose that there is product A(stock quantity = 10) & A1 (stock quantity = 10) ,A2(stock quantity = 20),A3(stock quantity = 30) are variations of A.So i want to store all the above details in custom table.
My DB schema is {post_id bigint (20), user_id bigint (20), stock_quantity int (11),log_date DATE}
I am unable to read stock values for product variation.
My Code is –
function insert_custom_table($new_status, $old_status, $post )
{
global $post;
global $wpdb;
global $current_user;
if(isset($post->ID))
{
$current_post = $post->ID;
}
wp_get_current_user();
$user_id = $current_user->ID;
if ( $post->post_type !== 'product' ) {
return;
}else{
if ( 'publish' !== $new_status or 'publish' === $old_status ){
//Check if someone published a post first time.
return;
}else{
$prodcut_qty = get_post_meta($post->ID,'_stock');
//Unable to read stock values for product variations.
}
}
$stock_notes = 'New Stock';
$wpdb->insert( 'wp_woocommerce_stock_custom', array( 'post_ID' => $current_post, 'user_ID' => $user_id, 'stock_quantity'=> $prodcut_qty ,'notes'=> $stock_notes) );
}
I am using woocommerce 5.5.2
Update :
I found that if we want to read postmeta table immediate after publish the post,for this type of task hook added_post_meta works fine.
2
Answers
I got the solution:
I found that if we want to read postmeta table immediate after publish the post,for this type of task hook added_post_meta works fine.
I modified my previous code
I did some tests and this should do the trick