Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

php - Additional button in Woocommerce shop page and archives

I'd like to add a button next to "Add to Cart" on the product page that adds "-sample" to the product URL when clicked.

Example:

You're viewing Product 1's page and the URL is "http://www.example.com/shop/product-1/"

When you click on the button, it adds "-sample" to the URL "http://www.example.com/shop/product-1-sample/"

How can I achieve this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For woocommerce 3+ (only):

In woocommerce 3 you will use woocommerce_after_shop_loop_item action hook instead, as the hook woocommerce_after_add_to_cart_button will not work anymore.

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
function add_custom_button() {
    global $product;

    $product_link = $product->get_permalink();

    $sample_link = substr($product_link, 0, -1) . '-sample/';
    echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Get a sample", "my_theme_slug" )  . '</a>';
}

Code goes on function.php file of your active child theme (or active theme). Tested and works.


Before woocommerce 3:

This is possible using hook woocommerce_after_add_to_cart_button to add your additional button on product pages, using this custom function:

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
function add_custom_button() {
    global $product;

    $product_link = get_permalink( get_the_id() );

    $sample_link = substr($product_link, 0, -1) . '-sample/';
    echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Get a sample", "my_theme_slug" )  . '</a>';
}

This code goes on function.php file of your active child theme or theme.

This code is tested and fully functional.


Based on this: Add a button after add to cart and redirect it to some custom link in WooCommerce

And this: PHP - How to remove all specific characters at the end of a string?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...