JSFiddle - React, Tailwind, and code Playground
by lindychen
HTML
add_action( 'woocommerce_product_options_general_product_data', 'simple_product_with_external_url' );
function simple_product_with_external_url() {
global $product_object;
echo '<div class="options_group show_if_simple hidden">';
// External Url
woocommerce_wp_text_input( array(
'id' => '_ext_url_cust',
'label' => 'External Url',
'description' => 'Custom external URL',
'desc_tip' => 'true',
'placeholder' => 'Enter here your custom external URL'
) );
echo '</div>';
}
add_action( 'woocommerce_admin_process_product_object', 'save_simple_product_with_external_url' , 10, 1);
function save_simple_product_with_external_url( $product ) {
if( isset($_POST['_ext_url_cust']) && ! empty($_POST['_ext_url_cust']) && $product->is_type('simple') ) {
$product->update_meta_data( '_ext_url_cust', sanitize_url($_POST['_ext_url_cust']) );
}
}
add_filter( 'woocommerce_loop_add_to_cart_link',
'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
$external_url = get_post_meta( $product->get_id(), '_ext_url_cust', true );
if ( ! empty( $external_url ) ) {
// Set HERE your button link
$link = $product->get_permalink();
$html = '<a href="'.$link.'" class="button alt add_to_cart_button">'.__("Read More", "woocommerce").'</a>';
}
return $html;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'redirect_simple_product_with_external_url', 10, 1 );
function redirect_simple_product_with_external_url( $url ) {
$product_id = absint( $_REQUEST['add-to-cart'] );
$external_url = get_post_meta( $product_id, '_ext_url_cust', true );
$product = wc_get_product( $product_id );
if ( 'simple' == $product->get_type() && ! empty( $external_url ) )
$url = $external_url;
return $url;
}