Advertisement
designbymerovingi

Example: Woo reward based on percentage

Jul 8th, 2016
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.82 KB | None | 0 0
  1. /**
  2.  * Woo Point Rewards by Category
  3.  * Reward buyes with points for buying products.
  4.  * @version 1.0
  5.  */
  6. function mycred_woo_payout_reward_per_category( $order_id ) {
  7.  
  8.     // Make sure we do not crash our site if myCRED gets disabled
  9.     if ( ! function_exists( 'mycred' ) ) return;
  10.  
  11.     // Setup
  12.     $payouts = array(
  13.         'category-one'   => 10,
  14.         'category-two'   => 15,
  15.         'category-three' => 20
  16.     );
  17.  
  18.     // Get Order
  19.     $order = wc_get_order( $order_id );
  20.  
  21.     // Get items in order
  22.     $items = $order->get_items();
  23.  
  24.     $reward = 0;
  25.  
  26.     // Loop through each item to get the category they are in
  27.     foreach ( $items as $item ) {
  28.  
  29.         $product_id = absint( $item['product_id'] );
  30.  
  31.         // Get all the categories this product is in
  32.         $categories = wp_get_object_terms( $product_id, 'product_cat', array( 'fields' => 'slugs' ) );
  33.  
  34.         // Default payout is 10%
  35.         $percentage_to_pay = 10;
  36.  
  37.         if ( ! empty( $categories ) ) {
  38.  
  39.             // Assuming each product is only in maximum 1 category!
  40.             $category_slug = $categories[0];
  41.  
  42.             // Find where our category slug fits in our $payouts setup
  43.             if ( array_key_exists( $category_slug, $payouts ) )
  44.                 $percentage_to_pay = $payouts[ $category_slug ];
  45.  
  46.         }
  47.  
  48.         // Calculate reward = x (percentage) of ( product price x quantity )
  49.         $reward += ( ( $item['line_subtotal'] * $item['qty'] ) * ( 1 + ( $percentage_to_pay / 100 ) ) );
  50.  
  51.     }
  52.  
  53.     // Zero points = no payout
  54.     if ( $reward == 0 ) return;
  55.  
  56.     // Load myCRED
  57.     $mycred = mycred();
  58.  
  59.     // Make sure we only payout once per order
  60.     if ( ! $mycred->has_entry( 'reward', $order_id, $order->user_id ) )
  61.         $mycred->add_creds(
  62.             'reward',
  63.             $order->user_id,
  64.             $reward,
  65.             'Points reward for store purchase',
  66.             $order_id,
  67.             array( 'ref_type' => 'post' )
  68.         );
  69.  
  70. }
  71. add_action( 'woocommerce_payment_complete', 'mycred_woo_payout_reward_per_category' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement