'How to call a function after new WooCommerce product is published manually
I am trying to create an extra WooCommerce product whenever a product is being created manually.
This is what i tried:
add_action('transition_post_status', 'on_product_creation', 10, 3);
function on_product_creation($new_status, $old_status, $post) {
if(
$old_status != 'publish'
&& $new_status == 'publish'
&& !empty($post->ID)
&& in_array( $post->post_type,
array( 'product')
)
) {
$post_data = array(
'post_name' => 'test2',
'post_title' => 'test2',
'post_status' => 'publish',
'post_type' => 'product',
);
$product_id = wp_insert_post( $post_data );
$product = new WC_Product_Subscription( $product_id );
$product->set_regular_price( 1 );
$product->set_price( 1 );
$product->save();
$id = $product->get_id();
update_post_meta($id, "_subscription_length", 12);
update_post_meta($id, "_subscription_price", 1);
$log = "productCreated";
file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);
}
}
For some reason my function doesn't run after I create a product.
I am trying to fire the hook only when the product been created manually to avoid recursion (a product creation will trigger itself) is there a way to know how the product have been created ?
Solution 1:[1]
This hook woocommerce_process_product_meta will run only when the product is manually created/updated. Tested OK with WC 6.2
/**
* Save meta box data.
*
* @param int $post_id WP post id.
* @param WP_Post $post Post object.
*/
function action_woocommerce_process_product_meta($post_id, $post) {
// make action magic happen here...
$product = new WC_Product_Simple();
$product->set_name('Sample product');
$product->set_status('publish');
$product->set_catalog_visibility('visible');
$product->set_price(19.99);
$product->set_regular_price(19.99);
$product->set_sold_individually(true);
$product->save();
}
// add the action
add_action('woocommerce_process_product_meta', 'action_woocommerce_process_product_meta', 10, 2);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
