Skip to content

Instantly share code, notes, and snippets.

@BurlesonBrad
Last active April 26, 2021 21:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BurlesonBrad/f1117afdf71322c36cc924b226de08a4 to your computer and use it in GitHub Desktop.
Save BurlesonBrad/f1117afdf71322c36cc924b226de08a4 to your computer and use it in GitHub Desktop.
Per Product Redirect for EVERY WooCommerce Product https://woocamp.com
<?php /* <--------Careful! */
/**
* Plugin Name: Per product Redirect
* Description: Empowers WooCommerce Store owners to add a custom redirect page on add-to-cart for EVERY product
* Version: 1.0.0
* Author: Brad Griffin
* Author URI: https://woocamp.com
* License: GNU General Public License v3.0
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
add_action( 'woocommerce_product_options_general_product_data', 'bkg_woo_add_custom_general_fields_woo_add_custom_general_fields' );
function bkg_woo_add_custom_general_fields_woo_add_custom_general_fields() {
global $post_id, $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input(
array(
'id' => '_bkg_woo_add_custom_general_fields_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' ) ,
'value' => get_post_meta( $post_id, '_bkg_woo_add_custom_general_fields_woo_product_custom_redirect_url', true )
)
);
echo '</div>';
}
//* Save Fields
add_action( 'woocommerce_process_product_meta', 'bkg_woo_add_custom_general_fields_woo_add_custom_general_fields_save' );
function bkg_woo_add_custom_general_fields_woo_add_custom_general_fields_save( $post_id ){
$bkg_woo_add_custom_general_fields_woo_redirect_url = $_POST['_bkg_woo_add_custom_general_fields_woo_product_custom_redirect_url'];
if ( ! empty( $bkg_woo_add_custom_general_fields_woo_redirect_url ) ) {
update_post_meta( $post_id, '_bkg_woo_add_custom_general_fields_woo_product_custom_redirect_url', esc_url( $bkg_woo_add_custom_general_fields_woo_redirect_url ) );
}
}
//* Redirect to URL
add_filter( 'woocommerce_add_to_cart_redirect', 'bkg_woo_add_custom_general_fields_redirect_to_url' );
function bkg_woo_add_custom_general_fields_redirect_to_url() {
global $woocommerce, $post;
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );
$bkg_woo_add_custom_general_fields_woo_redirect_url = get_post_meta( $product_id, '_bkg_woo_add_custom_general_fields_woo_product_custom_redirect_url', true );
if ( ! empty( $bkg_woo_add_custom_general_fields_woo_redirect_url ) ) {
wp_redirect( esc_url( $bkg_woo_add_custom_general_fields_woo_redirect_url ) ); exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment