Add s2Member Custom Capability on Completed Woocommerce Order

If you are managing or looking to manage a WordPress backed website with eCommerce capabilities and user management, WooCommerce and s2Member are the perfect WordPress plugins to get the job done. Both plugins are popular solutions for WordPress website owners and webmasters with Woocommerce having over 3 million active installs and s2Member with over 30,000 active installs.

What is WooCommerce

WooCommerce is a free WordPress plugin that adds eCommerce solution allowing you to sell anything, from virtual products to physical products, right from your WordPress backed website. WooCommerce offers tons of flexibility in configuring your store, from taxes, stock levels, shipping to payments options.

You can download WooCommerce from the WordPress Plugin repository, here

What is s2Member

s2Member is a powerful memberships plugin allowing WordPress website managers to set up a paid membership website that manages WordPress user’s roles and capabilities. With s2Member, website owners can protect their content including downloadable files and streaming video and audio. s2Member is powered almost entirely by WordPress shortcodes making integration easy for even the most novice user.

You can download s2Member from the WordPress Plugin repository, here

Although s2Member has the ability to manage payments with PayPal (Free Version) and other popular payment gateways with the Pro version, using a true eCommerce solution like WooCommerce and its plethora of features might make more sense. Offering custom capabilities and roles on your website where WooCommerce handles payments and s2Member manages permissions is a matter of hooking into WooCommerce functions.

The function below hooks into WooCommerce’s Order Status Completed adding your s2Member custom capabilities and/or roles. Place the function in your theme’s functions.php file.

function my_woocommerce_order_status_completed( $order_id ) {
  $order = wc_get_order( $order_id );
  $items = $order->get_items();
  $customer = $order->get_user();
  $user_id = $order->get_user_id();
  $user = new WP_User($user_id);

  foreach ( $items as $item ) {
    $product_name = $item->get_name();
    $product_id = $item->get_product_id();

    if ($product_id == '1') {
      $user->add_cap('access_s2member_level1');
      $user->add_cap('access_s2member_ccap_MYCAP');
    }
 }
}
add_action( 'woocommerce_order_status_completed', 'my_woocommerce_order_status_completed', 10, 1 );

The custom function looks for a completed WooCommerce order with payment received, collects the user and product details from the order. If the order contains product id 1, a custom capability is added along with s2Member access level 1.