【问题标题】:Replace add to cart button based on weight in WooCommerce single products在 WooCommerce 单品中根据重量替换添加到购物车按钮
【发布时间】:2021-01-25 05:37:28
【问题描述】:

我在 woocommerce 上搜索了有条件地替换添加到购物车按钮。我得到了一个代码,并根据我的需要对其进行了修改。它在商店页面上完美运行。

这是我的代码:

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_default_button', 10, 2 );
function replace_default_button( $button, $product ){
    global $product;
    $weight = $product->get_weight();
    preg_replace('/\D/', '', $weight);
    if ( $product->has_weight() && ($weight > '8') ){
        $button = '<a href="#" class="button alt">' . __( "Add to Quote", "woocommerce" ) . '</a>';
    }
    return $button;
}

但对于单个产品页面,我也需要类似的代码。 我该怎么做?有什么帮助吗?

【问题讨论】:

    标签: php wordpress button woocommerce hook-woocommerce


    【解决方案1】:

    首先你可以简化你的代码:

    add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_default_button', 10, 2 );
    function replace_default_button( $button, $product ){
    
        $weight = $product->get_weight();
        preg_replace('/\D/', '', $weight);
    
        if ( $weight > 8 ){
            $button = '<a href="#" class="button alt">' . __( "Add to Quote", "woocommerce" ) . '</a>';
        }
        return $button;
    }
    

    然后,要为单个产品页面提供类似的内容,请使用以下内容:

    add_action( 'woocommerce_single_product_summary', 'action_single_product_summary_callback', 1 );
    function action_single_product_summary_callback() {
        global $product;
    
        $weight = $product->get_weight();
        preg_replace('/\D/', '', $weight);
    
        if ( $weight > 8 ) {
    
            // For variable product types
            if( $product->is_type( 'variable' ) ) {
                remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
                add_action( 'woocommerce_single_variation', 'add_to_quote_replacement_button', 20 );
            }
            // For all other product types
            else {
                remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
                add_action( 'woocommerce_single_product_summary', 'add_to_quote_replacement_button', 30 );
            }
        }
    }
    
    function add_to_quote_replacement_button(){
        echo '<a href="#" class="button alt">' . __( "Add to Quote", "woocommerce" ) . '</a>';
    }
    

    代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 2019-08-04
      • 2018-03-05
      • 2018-10-04
      相关资源
      最近更新 更多