Created
August 17, 2018 01:56
-
-
Save ngearing/506f1f1b163bb0670b10a5693dbfa65c to your computer and use it in GitHub Desktop.
Create a MemberPress Member
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create a MemberPress Member trans and subscr record to activate a user. | |
* | |
* @param int $user_id WP_User id. | |
* @param int $membership_id WP_Post id. | |
* @return void | |
*/ | |
function create_memberpress_member( $user_id, $membership_id ) { | |
global $wpdb; | |
$key = "memberpressproduct_{$membership_id}_meta"; | |
if ( wp_cache_get( $key ) ) { | |
$meta = wp_cache_get( $key ); | |
} else { | |
$meta = $wpdb->get_results( | |
$wpdb->prepare( | |
"SELECT meta_key, meta_value | |
FROM $wpdb->postmeta | |
WHERE post_id = %s", | |
$membership_id | |
), ARRAY_N | |
); | |
wp_cache_set( $key, $meta ); | |
} | |
if ( ! $meta ) { | |
return; | |
} else { | |
$metadata = []; | |
foreach ( $meta as $m ) { | |
$metadata[ $m[0] ] = $m[1]; | |
} | |
} | |
// Create subscription. | |
$table = $wpdb->prefix . 'mepr_subscriptions'; | |
$data = [ | |
'user_id' => $user_id, | |
'product_id' => (int) $membership_id, | |
'subscr_id' => 'mp-sub-' . uniqid(), | |
'price' => $metadata['_mepr_product_price'], | |
'total' => $metadata['_mepr_product_price'], | |
'gateway' => 'manual', | |
'period' => $metadata['_mepr_product_period'], | |
'period_type' => $metadata['_mepr_product_period_type'], | |
'limit_cycles_num' => $metadata['_mepr_product_limit_cycles_num'], | |
'limit_cycles_action' => $metadata['_mepr_product_limit_cycles_action'], | |
'status' => 'active', | |
'created_at' => date( 'Y-m-d H:i:s' ), | |
]; | |
$inserted = $wpdb->insert( $table, $data ); | |
$sub_id = $wpdb->insert_id; | |
$increment = $metadata['_mepr_expire_after'] . ' ' . $metadata['_mepr_expire_unit']; | |
$expire = date( 'Y-m-d H:i:s', strtotime( "+$increment", time() ) ); | |
// Create transaction. | |
$table = $wpdb->prefix . 'mepr_transactions'; | |
$data = [ | |
'amount' => $metadata['_mepr_product_price'], | |
'total' => $metadata['_mepr_product_price'], | |
'user_id' => $user_id, | |
'product_id' => (int) $membership_id, | |
'trans_num' => 'mp-txn-' . uniqid(), | |
'status' => 'complete', | |
'gateway' => 'manual', | |
'subscription_id' => $sub_id, | |
'created_at' => date( 'Y-m-d H:i:s' ), | |
'expires_at' => $expire, | |
]; | |
$inserted = $wpdb->insert( $table, $data ); | |
$insert_id = $wpdb->insert_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment