<?php
/*
Plugin Name: MS2 Assign Memberships
Plugin URI: https://premium.wpmudev.org/project/membership/
Description: Gets a list of wordpress users and assign them to a membership or list of memberships
Author: Mahlamusa @ WPMU DEV
Version: 1.0.0
Author URI: https://premium.wpmudev.org/profile/mahlamusa
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
register_activation_hook(__FILE__, array('MS_Assign_Members_To_Memberships', 'add_cron_job') );
register_deactivation_hook(__FILE__, array('MS_Assign_Members_To_Memberships', 'deactivate_cron') );
class MS_Assign_Members_To_Memberships{
private $how_many; // how many user per batch
private $memberships; //array of membership ids to add to users.
private $offset; //
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new MS_Assign_Members_To_Memberships();
}
return self::$_instance;
}
public function __construct(){
$this->how_many = 100;
$this->memberships = array('1','2'); //TODO: Provide interface to select the memberships
$offset = get_option("ms_members_offset");
$this->offset = ( $offset != "" ) ? (int) $offset : 0;
add_action('init', array( $this, 'add_cron_job' ) );
add_filter('cron_schedules',array( $this, 'cron_schedules') ;
add_action('assign_members_to_memberships', 'do_assign_members_to_memberships', 10, 1);
}
public function add_cron_job(){
if (! wp_next_scheduled ( 'assign_members_to_memberships' )) {
wp_schedule_event(time(), 'everyminute', 'assign_members_to_memberships');
}
}
public function do_assign_members_to_memberships(){
set_time_limit(500); //allow 500 seconds for this to run
$users = $this->ms_get_wp_users();
//Memberships not included will be removed so also include current memberships if any.
foreach ( $users as $user ) {
MS_Controller_Member::assign_memberships( $user->ID, $this->memberships );
}
update_option('ms_members_offset', $offset + $this->how_many ); //update offset for next cron run
}
public function ms_get_wp_users(){
//TODO: Filter the users based on defined variables/meta to avoid adding all users to the membership unless that is required
//TODO: Add interface to filter the users based on specific creteria
$args = array(
'blog_id' => get_current_blog_id(),
'role' => 'subscriber',
'offset' => $this->offset,
'number' => $this->how_many
);
$users = get_users( $args );
if ( ! $users || is_wp_error( $users ) ) {
$this->deactivate_cron();
}
return $users;
}
public function cron_schedules($schedules){
if(!isset($schedules["everyminute"])){
$schedules["everyminute"] = array(
'interval' => 60,
'display' => __('Once every Minute')
);
}
return $schedules;
}
public function deactivate_cron() {
wp_clear_scheduled_hook('assign_members_to_memberships');
}
}
add_action( 'plugins_loaded', 'ms_assign_members_to_memberships', 10 );
function ms_assign_members_to_memberships(){
$GLOBALS['MS_Assign_Members_To_Memberships'] = MS_Assign_Members_To_Memberships::get_instance();
}