| 1 |
<?php |
| 2 |
/** |
| 3 |
* Add Membership |
| 4 |
* |
| 5 |
* @package AutomatorWP\Integrations\WooCommerce\Actions\Add_Membership |
| 6 |
* @author AutomatorWP <[email protected]>, Ruben Garcia <[email protected]> |
| 7 |
* @since 1.0.0 |
| 8 |
*/ |
| 9 |
// Exit if accessed directly |
| 10 |
if( !defined( 'ABSPATH' ) ) exit; |
| 11 |
|
| 12 |
class AutomatorWP_WooCommerce_Add_Membership extends AutomatorWP_Integration_Action { |
| 13 |
|
| 14 |
public $integration = 'woocommerce'; |
| 15 |
public $action = 'woocommerce_add_membership'; |
| 16 |
|
| 17 |
/** |
| 18 |
* Register the trigger |
| 19 |
* |
| 20 |
* @since 1.0.0 |
| 21 |
*/ |
| 22 |
public function register() { |
| 23 |
|
| 24 |
automatorwp_register_action( $this->action, array( |
| 25 |
'integration' => $this->integration, |
| 26 |
'label' => __( 'Add user to membership', 'automatorwp' ), |
| 27 |
'select_option' => __( 'Add user to <strong>membership</strong>', 'automatorwp' ), |
| 28 |
/* translators: %1$s: Membership. */ |
| 29 |
'edit_label' => sprintf( __( 'Add user to %1$s', 'automatorwp' ), '{post}' ), |
| 30 |
/* translators: %1$s: Membership. */ |
| 31 |
'log_label' => sprintf( __( 'Add user to %1$s', 'automatorwp' ), '{post}' ), |
| 32 |
'options' => array( |
| 33 |
'post' => automatorwp_utilities_post_option( array( |
| 34 |
'name' => __( 'Membership:', 'automatorwp' ), |
| 35 |
'option_default' => __( 'membership', 'automatorwp' ), |
| 36 |
'placeholder' => __( 'Select a membership', 'automatorwp' ), |
| 37 |
'option_none' => false, |
| 38 |
'option_custom' => true, |
| 39 |
'option_custom_desc' => __( 'Membership ID', 'automatorwp' ), |
| 40 |
'post_type' => 'wc_membership_plan', |
| 41 |
) ), |
| 42 |
), |
| 43 |
) ); |
| 44 |
|
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Action execution function |
| 49 |
* |
| 50 |
* @since 1.0.0 |
| 51 |
* |
| 52 |
* @param stdClass $action The action object |
| 53 |
* @param int $user_id The user ID |
| 54 |
* @param array $action_options The action's stored options (with tags already passed) |
| 55 |
* @param stdClass $automation The action's automation object |
| 56 |
*/ |
| 57 |
public function execute( $action, $user_id, $action_options, $automation ) { |
| 58 |
|
| 59 |
// Shorthand |
| 60 |
$membership_id = absint( $action_options['post'] ); |
| 61 |
|
| 62 |
// Bail if not membership provided |
| 63 |
if( $membership_id === 0 ) { |
| 64 |
return; |
| 65 |
} |
| 66 |
|
| 67 |
$is_user_member = wc_memberships_is_user_member( $user_id, $membership_id ); |
| 68 |
|
| 69 |
// Bail if user is already on this membership |
| 70 |
if ( $is_user_member ) { |
| 71 |
return; |
| 72 |
} |
| 73 |
|
| 74 |
// Add user to this membership |
| 75 |
wc_memberships_create_user_membership( array( |
| 76 |
'plan_id' => $membership_id, |
| 77 |
'user_id' => $user_id |
| 78 |
) ); |
| 79 |
|
| 80 |
} |
| 81 |
|
| 82 |
} |
| 83 |
|
| 84 |
new AutomatorWP_WooCommerce_Add_Membership(); |