Prevent categories from being overwritten during a Product Set update

By default, the Product Sets plugin will overwrite any category customizations you have made to a product when the Product Set updates. Generally, ALL product-category associations should be made at the Product Set level.

If however you need more control over the categories your products appear in, you can use the following code to prevent your custom product categorizations from being overwritten during a Product Set update.

1

Create a custom plugin

If you haven't done so already, create a custom plugin.

2

Add code

Add the following code to your custom plugin:

/**
 * See https://datafeedrapi.helpscoutdocs.com/article/218-prevent-categories-from-being-overwritten-during-a-product-set-update
 */
add_action( 'dfrpswc_post_save_product', static function ( Dfrpswc_Product_Update_Handler $updater ) {

   /**
    * If you change the ACF Field Name, you will need to update this value
    * to match the new Field Name.
    */
   $custom_override_field_name = 'dfrpswc_mycode_product_category_overrides';

   /**
    * If you want to set your Override Terms the same as your Product Set WooCommerce Category IDs
    * during the initial insert of the product, then set this value to true.
    *
    * Note: Doing so will effectively render your WooCommerce Category selection at the Product Set
    * level useless and all product category settings will need to be made manually.
    */
   $initialize_override_category_selection_with_categories_from_product_set = false;

   /** Stop editing here */

   if ( $updater->action === 'insert' ) {
      if ( $initialize_override_category_selection_with_categories_from_product_set ) {
         $product_set_term_ids = dfrps_get_cpt_terms( $updater->product_set['ID'] );
         update_field( $custom_override_field_name, $product_set_term_ids, $updater->post['ID'] );
      }

      return;
   }

   // Get ACF Term IDs.
   $term_ids = get_field( $custom_override_field_name, $updater->post['ID'], false );

   // If there are no $term_ids, this means that there are no Override values to use. Just return.
   if ( empty( $term_ids ) ) {
      return;
   }

   $updater->wc_product->set_category_ids( array_values( $term_ids ) );
   $updater->wc_product->save();
} );
3

Save

Save your custom code.

4

Add ACF Field Group

Install and activate the free version of the ACF plugin. Then go here WordPress Admin Area > Custom Fields > Tools and Import the attached Field Group: acf-category-overrides.json

Now on any Product page you want to change the category for you will see 2 lists of WooCommerce Product Categories. 

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us