Home > Software design >  Woocommerce redirect after checkout based on product custom field
Woocommerce redirect after checkout based on product custom field

Time:10-31

So i have custom text field meta in the product so that if has a url i would like to redirect users to a custom TY page after checkout. Here is my code and not redirecting!!

add_action('template_redirect', 'my_redirect_after_purchase');
function my_redirect_after_purchase() {
    global $post, $wp;

    $my_redirect = get_post_meta( get_the_ID(), '_my_redirect', true ); // This has the redirect URL entered in the field tested and working
    if ( '' !== $my_redirect ) { // am checking here if the field is not empty

        if (!empty($wp->query_vars['order-received'])) {

                    wp_redirect(esc_url($my_redirect)); 
            exit;
        }
    }
}

I have tried few other ways but no luck too. Am guessing the query for order-recieved runs after and thus the meta returns empty?

How should i go about this? Thanks

CodePudding user response:

First, you have to get order items using wc_get_order then you can get meta based on product id. Try the below code.

add_action('template_redirect', 'my_redirect_after_purchase');
function my_redirect_after_purchase() {

    /* return if we are not on order-received page */
    if( !is_wc_endpoint_url( 'order-received' ) || empty( $_GET['key'] ) ) {
        return;
    }
    
    $order_id = wc_get_order_id_by_order_key( $_GET['key'] );
    $order = wc_get_order( $order_id );

    foreach( $order->get_items() as $item ) {
        $my_redirect = get_post_meta( $item['product_id'] , '_my_redirect', true );
        if( $my_redirect != '' ){
            wp_redirect( $my_redirect );
            exit;
        }
    }

}
  • Related