Advertisement
palsushobhan

allowed_category_restriction_during_product_import

Jul 15th, 2024 (edited)
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.80 KB | None | 0 0
  1. add_action( 'woocommerce_product_import_before_process_item', function($data) {
  2.     if(empty($data['category_ids'])) return;
  3.     if(wcfm_is_vendor()) {
  4.         $vendor_id = apply_filters('wcfm_current_vendor_id', get_current_user_id());
  5.     } elseif(isset($data['store'])) {
  6.         $vendor_id = $data['store'];
  7.     } elseif(isset($data['meta_data'])) {
  8.         foreach($data['meta_data'] as $meta) {
  9.             if($meta['key'] == '_wcfm_product_author') {
  10.                 $vendor_id = $meta['value'];
  11.                 break;
  12.             }
  13.         }
  14.     }
  15.     if($vendor_id) {
  16.         $cache_key = 'wcfm-vendor-capabilities-' . $vendor_id;
  17.         $vendor_capability_options = wp_cache_get( $cache_key, 'wcfm-vendor-capabilities' );
  18.  
  19.         if( empty( $vendor_capability_options ) ) {
  20.             $vendor_capability_options = (array) apply_filters( 'wcfmgs_user_capability', get_option( 'wcfm_capability_options' ), $vendor_id );
  21.             wp_cache_set( $cache_key, $vendor_capability_options, 'wcfm-vendor-capabilities' );
  22.         }
  23.         $allowed_categories = $vendor_capability_options['allowed_categories'] ?? [];
  24.         if(empty($allowed_categories)) return;
  25.         foreach($data['category_ids'] as $cat_id) {
  26.             $category = get_term($cat_id, 'product_cat');
  27.             if (is_wp_error($category) || !$category) {
  28.                 continue;
  29.             }
  30.             if ($category->parent == 0 && in_array($cat_id, $allowed_categories)) {
  31.                 return;
  32.             }
  33.             while ($category->parent != 0) {
  34.                 $category = get_term($category->parent, 'product_cat');
  35.             }
  36.             if(in_array($category->term_id, $allowed_categories)) {
  37.                 return;
  38.             }
  39.         }
  40.         throw new Exception( 'category not allowed' );
  41.     }
  42. } );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement