How to redirect PMPRO(PaidMembership pro) to Cart

Emmanuel

Administrator
Staff member
May 11, 2020
125
28
84
Today I was working on Freelance Job for a client on Fiverr, and I have to write a code to redirect users to WooCommerce Cart whenever they purchase a membership plan, I have to search the internet for a code because am sure I wasn't the first person to look for this, but I couldn't find the right answer, after a little search I came across a code by WPLMS to redirect users to checkout page on membership purchase, so I just copied the code and modified it, here is the code in case you ever need it.


Code:
//function added by cuteblogger for pmpro redirect to cart
add_action('template_redirect','pmpro_woocommerce_redirect_checkout');
function pmpro_woocommerce_redirect_checkout(){
  $id = get_option('pmpro_checkout_page_id');
  global $post;
  if($post->ID == $id && !empty($_REQUEST['level'])){
    global $wpdb;
    $product_id = $wpdb->get_var($wpdb->prepare("SELECT pm.post_id FROM {$wpdb->postmeta} as pm LEFT JOIN {$wpdb->posts} as p ON p.ID=pm.post_id WHERE pm.meta_key = %s AND pm.meta_value = %d AND p.post_status='publish'",'_membership_product_level',$_REQUEST['level']));
    if(!empty($product_id)){
        $cart_url = WC()->cart->get_cart_url();
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
          foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->id == $product_id )
                $found = true;
          }
          // if product not found, add it
          if ( ! $found )
            WC()->cart->add_to_cart( $product_id );
          wp_redirect( $cart_url); 
        }else{
          // if no products in cart, add it
          WC()->cart->add_to_cart( $product_id );
          wp_redirect( $cart_url); 
        }
        exit();
    }
    
  }
}