Skip Navigation

[Closed] Setting initial_stock custom field from woocommerce _stock field

This support ticket is created 3 years, 9 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Our next available supporter will start replying to tickets in about 2.02 hours from now. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 3 years, 9 months ago.

Assisted by: Christian Cox.

Author
Posts
#1711307

I have used the following function to set an initial stock custom field, works great. But I would like it only be set when a specific product_cat is met.

Working function:

//create initial stock from _Stock.
add_action('cred_save_data','func_initial_stock',10,2);
function func_initial_stock($post_id,$form_data) {

if ($form_data['id']==9999) {
$stock = get_post_meta($post_id, '_stock', true);
update_post_meta($post_id, 'wpcf-initial-stock', $stock);
}
}

I wanted to add "if product_cat" to the function. Not working:

//create initial stock from _Stock.
add_action('cred_save_data','func_initial_stock',10,2);
function func_initial_stock($post_id,$form_data) {

if ($form_data['id']==9999) {
if ($form_data['product_cat']== 'specific_cat_slug') {
$stock = get_post_meta($post_id, '_stock', true);
update_post_meta($post_id, 'wpcf-initial-stock', $stock);
}
}
}

Any thoughts?
Thank you.

#1711787

Hi, since a taxonomy field supports multiple terms, the conditional syntax is array-based and a bit more complex. It's simpler to use the built-in WordPress function has_term to test whether the post has a specific term from a specific taxonomy:

if ( has_term( 'specific-term-slug', 'product_cat', $post_id ) ) {
  $stock = get_post_meta($post_id, '_stock', true);
  update_post_meta($post_id, 'wpcf-initial-stock', $stock);
}

More information about this function:
https://developer.wordpress.org/reference/functions/has_term/

Let me know if you have questions about this implementation.

The topic ‘[Closed] Setting initial_stock custom field from woocommerce _stock field’ is closed to new replies.