WooCommerce+WCVendor:实现商家与商品位置分类自动同步
自动同步WCVendor商家位置到商品Product Location分类法
Hey there, let's cut out that tedious manual location selection for your vendors! I've put together a complete code solution based on your WooCommerce + WCVendor setup that automatically syncs a vendor's location taxonomy to their products' Product Location taxonomy whenever a product is added or updated:
// Prevent infinite loop flag $mp_sync_in_progress = false; add_action( 'added_post_meta', 'mp_sync_on_product_save', 10, 4 ); add_action( 'updated_post_meta', 'mp_sync_on_product_save', 10, 4 ); function mp_sync_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) { global $mp_sync_in_progress; // Exit if sync is already running or we're not dealing with a WooCommerce product if ( $mp_sync_in_progress || get_post_type( $post_id ) !== 'product' ) { return; } // Grab the vendor's user ID (WCVendor ties vendors to WordPress user accounts via post author) $vendor_user_id = get_post_field( 'post_author', $post_id ); if ( ! $vendor_user_id ) { return; } // Fetch the vendor's assigned location terms (adjust taxonomy slug if yours differs) $vendor_locations = wp_get_object_terms( $vendor_user_id, 'location', array( 'fields' => 'ids' ) ); if ( empty( $vendor_locations ) ) { return; } // Set loop prevention flag to stop the code from triggering itself $mp_sync_in_progress = true; // Sync the vendor's location to the product's Product Location taxonomy (adjust slug if needed) wp_set_object_terms( $post_id, $vendor_locations[0], 'product_location', false ); // Reset the flag for future operations $mp_sync_in_progress = false; }
Key Details & Customization Tips:
- Hook Coverage: We use both
added_post_metaandupdated_post_metato cover both new product creations and existing product edits. - Loop Prevention: The global
$mp_sync_in_progressflag stops the code from triggering itself when we update the product's location taxonomy (avoids infinite loops). - Taxonomy Slug Check: Double-check your actual taxonomy slugs! I used
locationfor the vendor taxonomy andproduct_locationfor the product taxonomy—if your slugs are different (e.g.,product-locationinstead ofproduct_location), update those values in the code. - Multiple Location Support: If your vendors can have multiple locations and you want to sync all of them, remove the
[0]from$vendor_locations[0]and change the last parameter ofwp_set_object_termsfromfalsetotrue(this appends terms instead of replacing them). - Safe Placement: Add this code to your child theme's
functions.phpfile or a custom plugin—never edit core WooCommerce/WCVendor files directly (you'll lose changes on updates).
内容的提问来源于stack exchange,提问作者Hasan
相关产品推荐
相关产品推荐

