I am creating an event ticketing WordPress theme and I am using WooCommerce and Advanced custom fields (ACF) plugins.
I want to update a custom post type called event. With the stock of a specific ticket. That way my client does not need to look at the woo-commerce products page but can just simply open an "Event"
I tried using the update_post_meta
hook but that only works when an admin updates the product in the admin tool. Not with a new order.
function sync_product_stock( $meta_id, $post_id, $meta_key, $meta_value ) {
$postType = get_post_type( $post_id );
if ($postType == 'product' ) {
if ( $meta_key == '_stock' ) {
$product = wc_get_product( $post_id );
$eventId = $product->get_attribute( 'event_id' );
$productName = $product->get_name();
if ($productName.include('Early Bird')) {
update_field( 'event_early_bird_group_event_early_bird_amount_of_tickets', $meta_value, $eventId );
} else if ($productName.include('Regular')) {
update_field( 'event_regular_group_event_regular_amount_of_tickets', $meta_value, $eventId );
} else if ($productName.include('Member')) {
// nothing needs to be updated
}
}
}
}
add_action( 'updated_post_meta', 'sync_product_stock', 10, 4);
How can I get notified when the _stock
field is updated? (I don't want to handle the stock-keeping myself
There are some mistakes in your code. Try the following using woocommerce hooks:
// On processed update product stock event
add_action( 'woocommerce_updated_product_stock', 'wc_updated_product_stock_callback' );
// On admin single product creation/update
add_action( 'woocommerce_process_product_meta', 'wc_updated_product_stock_callback' );
// On admin single product variation creation/update
add_action( 'woocommerce_save_product_variation', 'wc_updated_product_stock_callback' );
function wc_updated_product_stock_callback( $product_id ) {
// get an instance of the WC_Product Object
$product = wc_get_product( $product_id );
$stock_qty = $product->get_stock_quantity();
$event_id = $product->get_attribute('event_id');
$product_name = $product->get_name();
if ( strpos($product_name, 'Early Bird') !== false ) {
update_field( 'event_early_bird_group_event_early_bird_amount_of_tickets', $stock_qty, $event_id );
} elseif ( strpos($product_name, 'Regular') !== false ) {
update_field( 'event_regular_group_event_regular_amount_of_tickets', $stock_qty, $event_id );
} elseif ( strpos($product_name, 'Member') !== false ) {
// nothing needs to be updated
}
}
Code goes in function.php file of the active child theme (or active theme). It should work.