[英]Replace Add to cart button on Woocommerce Single Product Pages for a product category
[英]Replace add to cart button based on weight in WooCommerce single products
我已經在 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;
}
但我也需要單個產品頁面的類似代碼。 我該怎么做? 有什么幫助嗎?
首先,您可以簡化代碼,如下所示:
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文件。 測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.