Join

Create Unique Redirects Based on the Purchased Product

Don't want to mess with code snippets? This is a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

This code snippet adds a custom URL field to WooCommerce Products that you can use to specify a unique redirection based on the Product purchased.

The add_custom_field() function takes the Product ID as an input and sets the field’s label, placeholder, descr_tip, and description. The field is then added to the options group on the WooCommerce admin screen.

The process_product_meta() action is used to save the custom field information. The function takes the Product ID as an input and updates the post meta with the field name, label, placeholder, desc_tip, and description. If the post meta has a value, the function will also save the redirect URL for the field.

Once this code snippet is enabled, simply edit any WooCommerce Product, inputting the desired redirection URL.

add_action( 'woocommerce_product_options_general_product_data', 'wptu_woo_add_custom_general_fields' );
function wptu_woo_add_custom_general_fields() {
    global $woocommerce, $post;
    echo '<div class="options_group">';
    woocommerce_wp_text_input(
        array(
            'id' => '_wptu_woo_redirect_url',
            'label' => __( 'Redirect URL', 'woocommerce' ),
            'placeholder' => 'https://',
            'desc_tip' => 'true',
            'description' => __( 'Enter the URL the customer will be redirected to after purchasing this product.', 'woocommerce' )
        )
    );
    echo '</div>';
}
add_action( 'woocommerce_process_product_meta', 'wptu_woo_add_custom_general_fields_save' );
function wptu_woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_wptu_woo_redirect_url'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_wptu_woo_redirect_url', esc_attr( $woocommerce_text_field ) );
}
add_action( 'woocommerce_thankyou', 'wptu_woo_redirectcustom');
function wptu_woo_redirectcustom( $order_id ){
    $order = new WC_Order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];
    }
    $redirect = get_post_meta( $product_id, '_wptu_woo_redirect_url', true );
    if ( ! empty( $redirect ) ) {
        wp_redirect( $redirect );
        exit;
    }
}