geminilabs

[site-reviews] auto create/assign CPT category for reviews

May 9th, 2020
242
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * This snippet assumes that you have two CPT: Restaurant and Food,
  3.  * and that you have somehow connected these two post objects (i.e. A Restaurant has many Foods).
  4.  *
  5.  * Since Site Reviews v4 does not allow you to assign reviews to multiple Post IDs,
  6.  * the solution is to assign reviews to the Food CPT ID, and then have Site Reviews
  7.  * automatically assign the reviews to a restaurant category with slug that contains
  8.  * the Restaurant CPT Post ID. If the restaurant category does not exist, it will be
  9.  * created when a review is submitted. This category can then be used to target all
  10.  * food reviews for the restaurant.
  11.  *
  12.  * Please pay attention to the @todo in the snippet below
  13.  *
  14.  * If you need to manually create the restaurant categories for existing reviews,
  15.  * the category slug must look like this: "restaurant_123" where "123" is the
  16.  * Restaurant Post ID.
  17.  *
  18.  * @param \GeminiLabs\SiteReviews\Review $review
  19.  * @return void
  20.  */
  21. add_action('site-reviews/review/created', function ($review) {
  22.     $assignedToIds = array_filter((array) $review->assigned_to);
  23.     foreach ($assignedToIds as $foodPostId) {
  24.  
  25.         // @todo you need edit this part to get the associated restaurant post from the food post ID
  26.         $restaurantPostId = '';
  27.  
  28.         $restaurant = get_post($restaurantPostId);
  29.         if (empty($restaurant->ID)) {
  30.             continue;
  31.         }
  32.         $termSlug = 'restaurant_'.$restaurant->ID;
  33.         if (!term_exists($termSlug, glsr()->taxonomy)) {
  34.             wp_insert_term($restaurant->post_title, glsr()->taxonomy, ['slug' => $termSlug]);
  35.         }
  36.         wp_set_object_terms($review->ID, $termSlug, glsr()->taxonomy);
  37.     }
  38. });
RAW Paste Data Copied