Skip to content

Instantly share code, notes, and snippets.

@gabrielmerovingi
Created July 5, 2017 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gabrielmerovingi/e5db47c467c110ab2bad50e1752cb078 to your computer and use it in GitHub Desktop.
Save gabrielmerovingi/e5db47c467c110ab2bad50e1752cb078 to your computer and use it in GitHub Desktop.
For each completed WooCommerce order, give the product author 1 point for each product they sell. If the order is refunded, take those points away. Note that this will only run once per order.
/**
* Reward Store Sales
* @version 1.0
*/
function mycred_pro_reward_store_sales( $order_id ) {
// Prevent crashes if myCRED gets disabled
if ( ! function_exists( 'mycred' ) ) return;
// Get order
$order = wc_get_order( $order_id );
// Give 1 point x quantity under the reference "store_sale"
mycred_pro_run_for_order( $order, 1, 'store_sale', 'New completed order' );
}
add_action( 'woocommerce_payment_complete', 'mycred_pro_reward_store_sales' );
/**
* Deduct Store Refunds
* @version 1.0
*/
function mycred_pro_deduct_store_refund( $order_id ) {
// Prevent crashes if myCRED gets disabled
if ( ! function_exists( 'mycred' ) ) return;
// Get order
$order = wc_get_order( $order_id );
// Take 1 point x quantity under the reference "store_sale_refund"
mycred_pro_run_for_order( $order, -1, 'store_sale_refund', 'Refund of order' );
}
add_action( 'woocommerce_order_refunded', 'mycred_pro_deduct_store_refund' );
/**
* Run myCRED for Woo Order
* @version 1.0
*/
function mycred_pro_run_for_order( $order, $amount, $reference = '', $entry = '' ) {
// Prevent crashes if myCRED gets disabled
if ( ! function_exists( 'mycred' ) ) return;
$items = $order->get_items();
// Loop through items in order
foreach ( $items as $item ) {
$product_id = absint( $item['product_id'] );
$variation_id = absint( $item['variation_id'] );
// For variations we need to get the parent product
if ( $variation_id > 0 ) {
$product = get_post( $variation_id );
$product_id = $product->post_parent;
}
// Get product owner
$product = get_post( $product_id );
$product_owner = $product->post_author;
// Get myCRED
$mycred = mycred();
// If owner is not excluded give points
if ( ! $mycred->exclude_user( $product_owner ) ) {
// Multiply by the quantity amount
$amount = $amount * $item['qty'];
// Make sure we only do things once for each order
if ( ! $mycred->has_entry( $reference, $order_id, $product_owner, $product_id ) )
$mycred->add_creds(
$reference,
$product_owner,
$amount,
$entry,
$order_id,
$product_id
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment