Advertisement
geminilabs

[site-reviews] sync product categories with Site Reviews

Mar 13th, 2025
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.84 KB | None | 0 0
  1. function glsr_fn_assigned_product_catgeories (array $values) {
  2.     require_once ABSPATH.'wp-admin/includes/taxonomy.php';
  3.     foreach ($values['assigned_posts'] as $postId) {
  4.         // is this an assigned product?
  5.         if ('product' !== get_post_type($postId)) {
  6.             continue;
  7.         }
  8.         // get the product's attached categories
  9.         $productTerms = get_the_terms($postId, 'product_cat');
  10.         foreach ($productTerms as $productTerm) {
  11.             $term = term_exists($productTerm->slug, glsr()->taxonomy);
  12.             // does a Site Reviews category already exist for this product category?
  13.             if (!empty($term['term_taxonomy_id'])) {
  14.                 // if it does, add it to the assigned_terms array
  15.                 $values['assigned_terms'][] = $term['term_taxonomy_id'];
  16.                 continue;
  17.             }
  18.             // if it does not, try to create it
  19.             $term = wp_insert_term($productTerm->name, glsr()->taxonomy, [
  20.                 'description' => 'Woo ttid: '.$productTerm->term_taxonomy_id,
  21.                 'slug' => $productTerm->slug,
  22.             ]);
  23.             if (is_wp_error($term)) {
  24.                 // if there was an error then log it to the Site Reviews console
  25.                 glsr_log()->error($term->get_error_message());
  26.                 continue;
  27.             }
  28.             // if it does, add the newly created category to the assigned_terms array
  29.             $values['assigned_terms'][] = $term['term_taxonomy_id'];
  30.         }
  31.     }
  32.     // make sure the term taxonomy IDs in the array is unique
  33.     $values['assigned_terms'] = array_values(array_unique($values['assigned_terms']));
  34.     return $values;
  35. }
  36. add_filter('site-reviews/defaults/create-review', 'glsr_fn_assigned_product_catgeories');
  37. add_filter('site-reviews/defaults/reviews', 'glsr_fn_assigned_product_catgeories');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement