Ich versuche, ein zusätzliches WooCommerce-Produkt zu erstellen, wenn ein Produkt manuell erstellt wird.
Das habe ich versucht:
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);
}
}
Aus irgendeinem Grund wird meine Funktion nicht ausgeführt, nachdem ich ein Produkt erstellt habe.
Ich versuche, den Hook nur auszulösen, wenn das Produkt manuell erstellt wurde, um eine Rekursion zu vermeiden (eine Produkterstellung löst sich selbst aus). Gibt es eine Möglichkeit zu erfahren, wie das Produkt erstellt wurde?
Lösung des Problems
Dieser Hook woocommerce_process_product_meta
wird nur ausgeführt, wenn das Produkt manuell erstellt/aktualisiert wird. Getestet OK mit 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);
Keine Kommentare:
Kommentar veröffentlichen