|
<?php |
|
/* |
|
* When these hooks fire, check each item in the invoice, and set the stock of its parent, children and siblings to the same. |
|
*/ |
|
|
|
function item_stock_level_sync_dbg_log( $data ) { |
|
// error_log( print_r( $data, true ) ); |
|
} |
|
|
|
add_action( 'updated_postmeta', 'sync_related_items_stock_level', 10, 4 ); |
|
|
|
function sync_related_items_stock_level( $meta_id, $post_id, $meta_key, $meta_value ) { |
|
if ( $meta_key !== '_stock' || get_post_type( $post_id ) !== 'wpi_item' ) { |
|
return; |
|
} |
|
|
|
item_stock_level_sync_dbg_log( "Setting stock of item ID {$post_id} to {$meta_value}" ); |
|
|
|
// if this item has a parent and the parent's metadata isn't being updated, just update the meta value of the parent (which will trigger updating of all its children recursively) |
|
// otherwise, update the stock of all its children (which will trigger updating their children), while indicating this was done by the parent |
|
$parent = get_post_parent( $post_id ); |
|
if ( $parent && ! get_post_meta( $parent->ID, '_stock_is_locked', true ) ) { |
|
// it has a parent and this call wasn't triggered by the parent's stock level update => just update the parent's stock |
|
item_stock_level_sync_dbg_log( "Updating parent only" ); |
|
update_post_meta( $parent->ID, '_stock', $meta_value ); |
|
} else { |
|
// either no parent, or this call was triggered by the parent's stock level update => ignore parent and siblings, and only update children |
|
item_stock_level_sync_dbg_log( "Updating children only" ); |
|
update_post_meta( $post_id, '_stock_is_locked', true ); |
|
|
|
$children = get_children( array( |
|
'post_parent' => $post_id, |
|
'post_type' => 'wpi_item' |
|
) ); |
|
foreach ( $children as $child ) { |
|
update_post_meta( $child->ID, '_stock', $meta_value ); |
|
} |
|
|
|
update_post_meta( $post_id, '_stock_is_locked', false ); |
|
} |
|
} |
|
?> |