Let’s say I need to add a custom button so visitors can visit the product’s external site. That way they can visit the product’s site.
What I want to achieve is as follows:
- Add a custom button after the add to cart button;
- The link to the custom button needs to be set in each product edition.
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Welcome to WPSE.
You can use a WordPress WooCommerce hook to achive this. Just like WordPress itself, WooCommerce also allows you to use hooks and filters to customize your shop. You need to add the following code to the functions.php of your current theme.
This code adds a simple link after the WooCommerce add to cart button.
// This function gets the value for the the custom fields from the database and adds it to the frontend output function
function wpse_add_custom_link_output() {
$external_link = get_post_meta(get_the_ID(), '_custom_product_text_field', true);
$html = '<a href="'.$external_link.'" rel="nofollow noreferrer noopener" class="custom-button-class" target="_blank" title="'.__('External product link','woocommerce').'">'.$external_link.'</a>';
echo $html;
};
add_action( 'woocommerce_after_add_to_cart_button', 'wpse_add_custom_link_output', 10, 0 );
// This function creates the field in the backend
function wpse_add_custom_link_field(){
global $woocommerce, $post;
echo '<div class="product_custom_field">';
// Custom Product Text Field
woocommerce_wp_text_input(
array(
'id' => '_custom_product_text_field',
'placeholder' => __('Paste product link here', 'woocommerce'),
'label' => __('Custom product link', 'woocommerce'),
'desc_tip' => 'true'
)
);
echo '</div>';
}
add_action('woocommerce_product_options_general_product_data', 'wpse_add_custom_link_field');
// this function saves the link/text field
function wpse_save_custom_link_field($post_id){
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['_custom_product_text_field'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, '_custom_product_text_field',
esc_attr($woocommerce_custom_product_text_field));
}
add_action('woocommerce_process_product_meta', 'wpse_save_custom_link_field');
You may want to add some css like:
a.custom-button-class:link,
a.custom-button-class:visited {
display: block;
margin-top: 30px;
}
a.custom-button-class:hover,
a.custom-button-class:focus {
/* some hover style */
}
Please accept the answer as correct if it worked for you. I have tested this code with theme 2020.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0