Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // please do not make it public yet
- function extract_and_save_product_amounts( $event ) {
- $post = $event->post;
- // Ensure the post type is 'products'
- if ( $post->post_type->get_key() !== 'products' ) {
- return;
- }
- $post_id = $post->get_id(); // Use get_id() for Voxel compatibility
- // Get the 'product' custom field.
- $product_data = maybe_unserialize( get_post_meta( $post_id, 'product', true ) );
- // Debugging: Log the retrieved product data.
- error_log( "Extract Function triggered for post ID: $post_id" );
- error_log( "Raw product data: " . print_r( $product_data, true ) );
- // Check if the custom field exists and is not empty.
- if ( ! empty( $product_data ) ) {
- // Decode the JSON data.
- $product_array = json_decode( $product_data, true );
- // Validate structure and extract amounts.
- if ( is_array( $product_array ) && isset( $product_array['base_price']['amount'] ) ) {
- // Convert and round amount
- $amount = number_format(floatval($product_array['base_price']['amount']), 2, '.', '');
- // Update product_amount meta
- delete_post_meta( $post_id, 'product_amount' );
- update_post_meta( $post_id, 'product_amount', $amount );
- error_log( "Updated product_amount to: $amount" );
- // Handle product_discount_amount
- if ( isset($product_array['base_price']['discount_amount']) && $product_array['base_price']['discount_amount'] !== '' ) {
- $discount_amount = number_format(floatval($product_array['base_price']['discount_amount']), 2, '.', '');
- delete_post_meta( $post_id, 'product_discount_amount' );
- update_post_meta( $post_id, 'product_discount_amount', $discount_amount );
- error_log( "Updated product_discount_amount to: $discount_amount" );
- } else {
- // Delete the meta field if discount_amount is missing or empty
- delete_post_meta( $post_id, 'product_discount_amount' );
- error_log( "Deleted product_discount_amount for post ID: $post_id" );
- }
- } else {
- error_log( "Invalid JSON structure or missing 'amount' for post ID: $post_id" );
- }
- } else {
- error_log( "No product data found for post ID: $post_id" );
- }
- }
- // Hook into Voxel events
- add_action( 'voxel/app-events/post-types/products/post:submitted', 'extract_and_save_product_amounts' );
- add_action( 'voxel/app-events/post-types/products/post:updated', 'extract_and_save_product_amounts' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement