我在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文件中。经过测试和工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句