doupeng2253
2017-08-09 14:10
浏览 122
已采纳

woocommerce_single_product_summary hook中的重复添加到购物车按钮问题

Trying to turn the add to cart button into a download link on a Woocommerce site (for free downloadable items).

The code I have set up below does that, but it is also duplicating the add to cart button. So I end up with the file download link + an additional add to cart button.

What am I missing?

Here is that code:

remove_action( 'woocommerce_single_product_summary', 
'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 
'itl_woocommerce_template_single_add_to_cart', 30 );

/*
 * replace WooCommerce add-to-cart button with download link when product is 
downloadable & free
 */

function itl_woocommerce_template_single_add_to_cart() {
    global $product;
    if ( $product->is_downloadable('yes') ) {
        if ( $product->get_price() > 0 ) {
            do_action( 'woocommerce_' . $product->product_type . 
 '_add_to_cart' );
        } else {
            $downloads = $product->get_files();
            foreach( $downloads as $key => $download ) {
                echo '<p class="download-link"><a href="' . esc_url( 
$download['file'] ) . '">' . $download['name'] . '</a></p>';
            }
        }
    } else {
        do_action( 'woocommerce_' . $product->product_type . '_add_to_cart' );
    }
}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumu5662 2017-08-10 00:11
    已采纳

    I have revisited, corrected, compact and tested your code. So now its working for WC version 3+:

    add_action( 'woocommerce_single_product_summary', 'customizing_single_add_to_cart', 1 );
    function customizing_single_add_to_cart(){
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        add_action('woocommerce_single_product_summary', function(){
            global $product;
            if ( $product->is_downloadable() && $product->get_price() <= 0 )
                foreach( $product->get_downloads() as $key => $download )
                    echo '<p class="download-link"><a href="' . esc_url( $download['file'] ) . '">' . $download['name'] . '</a></p>';
            else
                woocommerce_template_single_add_to_cart();
        }, 30);
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested and works (in WooCommerce version 3+)

    打赏 评论

相关推荐 更多相似问题