Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Last active November 15, 2021 09:06
Show Gist options
  • Save andrewlimaza/f66e5d2f8b8307843570c230e5a73493 to your computer and use it in GitHub Desktop.
Save andrewlimaza/f66e5d2f8b8307843570c230e5a73493 to your computer and use it in GitHub Desktop.
Assign membership level based on variation product purchase.
<?php
/**
* Assign a membership level based on product ID variation purchase.
* Add this code below to your PMPro Customizations Plugin - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function add_membership_for_variation_pricing( $order_id ) {
global $wpdb, $pmprowoo_product_levels;
// quitely exit if PMPro isn't active
if ( ! defined( 'PMPRO_DIR' ) && ! function_exists( 'pmpro_init' ) ) {
return;
}
//get order
$order = new WC_Order( $order_id );
$user_id = $order->get_user_id();
if ( empty( $user_id ) ) {
return;
}
foreach ( $order->get_items() as $item ) {
if ( ! empty( $item['product_id'] ) && ! empty( $item['variation_id'] ) ) {
// match product variation ID's with membership levels.
switch ( $item['variation_id'] ) {
case 147:
if ( function_exists( 'pmprommpu_addMembershipLevel' ) ) {
// Allow filter to force add levels (ignore MMPU group level settings).
$mmpu_force_add_level = apply_filters( 'pmprowoo_mmpu_force_add_level', false );
pmprommpu_addMembershipLevel( '1', $user_id, $mmpu_force_add_level );
} else {
pmpro_changeMembershipLevel( '1', $user_id );
}
break;
case 148:
if ( function_exists( 'pmprommpu_addMembershipLevel' ) ) {
// Allow filter to force add levels (ignore MMPU group level settings).
$mmpu_force_add_level = apply_filters( 'pmprowoo_mmpu_force_add_level', false );
pmprommpu_addMembershipLevel( '2', $user_id, $mmpu_force_add_level );
} else {
pmpro_changeMembershipLevel( '2', $user_id );
}
break;
case 149:
if ( function_exists( 'pmprommpu_addMembershipLevel' ) ) {
// Allow filter to force add levels (ignore MMPU group level settings).
$mmpu_force_add_level = apply_filters( 'pmprowoo_mmpu_force_add_level', false );
pmprommpu_addMembershipLevel( '3', $user_id, $mmpu_force_add_level );
} else {
pmpro_changeMembershipLevel( '3', $user_id );
}
break;
}
}
}
}
add_action( "woocommerce_order_status_completed", "add_membership_for_variation_pricing" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment