How to add a custom button before Add to Cart form on WooCommerce Product Page? and I want different links for different products.
My PHP Code:
add_action( 'woocommerce_before_add_to_cart_form', 'learnalwayss_after_add_to_cart_btn' );
function learnalwayss_after_add_to_cart_btn() {
global $product;
if ( $product->get_id() == 149685 ) {
echo '<a class="button primary is-small box-shadow-4 box-shadow-2-hover" style="border-radius: 10px; background-color:#FFDB58 !important; color:black;" target="_blank" href="https://myurls.bio/learn_alwayss">Our Links</a>';
}
}
2
Answers
Your solution is simple and effective but you have to add every url manually in the source code.
The solution I am suggesting uses
wp_postmeta
to store the label and url of the button. This way, a regular user can add/change the value of the url instead of asking a developer to make every change.We’ll add 2 custom fields to the product page to store these values into metadata.
To add custom fields for the
custom_button_url
andcustom_button_text
metadata to the edit product page in WooCommerce, you can use thewoocommerce_product_options_general_product_data
hook to add the custom fields to the product data panel, and the woocommerce_process_product_meta hook to save the custom field values when the product is saved.And to save the values into the
wp_postmeta
you can usewoocommerce_process_product_meta
hookNow we only have to display the button using the
woocommerce_before_add_to_cart_form
hook. You can use any other hook on the product page to show the button in a different place.This code enables you to use WordPress or ACF custom fields to add unique button links.
Note : I wouldn’t add the styling inline. Better to add it in your child themes stylesheet. Source