• Resolved Ren Ventura

    (@engagewp)


    Hello everyone,

    I’ve set up a WooCommerce product option to accept a URL from the user and I’m trying to output this URL to complete a redirect. Everything is fine except the redirect part. I need some insight on passing the value of a custom input into the wp_redirect() function. Any advice would be very much appreciated.

    //* Add Redirect URL Field
    add_action( 'woocommerce_product_options_general_product_data', 'rv_woo_add_custom_general_fields' );
    function rv_woo_add_custom_general_fields() {
    	global $woocommerce, $post;
    	echo '<div class="options_group">';
    	woocommerce_wp_text_input(
    		array(
    			'id'          => '_rv_woo_product_custom_redirect_url',
    			'label'       => __( 'Redirect on Add to Cart', 'woocommerce' ),
    			'placeholder' => 'https://',
    			'desc_tip'    => 'true',
    			'description' => __( 'Enter a URL to redirect the user to after this product is added to the cart.', 'woocommerce' )
    		)
    	);
    	echo '</div>';
    }
    
    //* Save Redirect URL Field
    add_action( 'woocommerce_process_product_meta', 'rv_woo_add_custom_general_fields_save' );
    function rv_woo_add_custom_general_fields_save( $post_id ){
    	$rv_woo_redirect_url = $_POST['_rv_woo_product_custom_redirect_url'];
    	if( !empty( $rv_woo_redirect_url ) ) {
    		update_post_meta( $post_id, '_rv_woo_product_custom_redirect_url', esc_url( $rv_woo_redirect_url ) );
    	}
    }
    
    //* Redirect to URL
    add_filter('add_to_cart_redirect', 'rv_redirect_elsewhere');
    function rv_redirect_elsewhere() {
    	$rv_woo_redirect_url = get_post_meta( get_the_ID(), _rv_woo_product_custom_redirect_url, true );
    	if( !empty( $rv_woo_redirect_url ) ) {
    		wp_redirect( $rv_woo_redirect_url );
    		exit;
    	}
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Looks like you are missing quotes around the meta_key in this line:

    $rv_woo_redirect_url = get_post_meta( get_the_ID(), _rv_woo_product_custom_redirect_url, true );

    It should be this:

    $rv_woo_redirect_url = get_post_meta( get_the_ID(), '_rv_woo_product_custom_redirect_url', true );
    Thread Starter Ren Ventura

    (@engagewp)

    I was actually able to get this resolved. The issue was with not properly retrieving the ID of the product added to the cart before doing the redirect. Thanks for the response, though.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WordPress Redirect Using the Value of a Variable’ is closed to new replies.