【发布时间】:2021-04-21 03:57:03
【问题描述】:
如果商品已在购物车中,我会使用代码更改产品“添加到购物车”按钮的文本和样式。非常感谢 7uc1f3r。
/* for single product */
add_filter( 'woocommerce_product_single_add_to_cart_text', 'single_product_button_text' );
function single_product_button_text( $text ) {
if( WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( get_the_ID() ) ) ) {
$text = 'Product in cart';
}
return $text;
}
/* for archive/category pages */
add_filter( 'woocommerce_product_add_to_cart_text', 'products_button_text', 20, 2 );
function products_button_text( $text, $product ) {
if(
$product->is_type( 'simple' )
&& $product->is_purchasable()
&& $product->is_in_stock()
&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) )
) {
$text = 'Product in cart';
}
return $text;
}
function action_wp_footer() {
?>
<script>
jQuery(document).ready(function($) {
var selector = '.add_to_cart_text:contains("Product in cart")';
// Selector contains specific text
if ( $( selector ).length > 0 ) {
$( selector ).addClass( 'product-is-added' );
} else {
$( selector ).removeClass( 'product-is-added' );
}
});
</script>
<?php
}
add_action( 'wp_footer', 'action_wp_footer' );
将产品添加到购物车后,我必须每次刷新页面以获取新的文本和按钮样式。
更新
我还使用了 Relabel "add to cart" button after add to cart in WooCommerce 第二个功能代码来使用 AJAX 更改按钮的文本和样式。文本发生了变化,但所有样式都中断了。
很遗憾,在echo '<div class="add_to_cart_text">' . $new_text . '</div>'; 行上添加样式不起作用。
有什么帮助吗?
【问题讨论】:
-
@LoicTheAztec 我可以寻求帮助吗?您的代码有效,“购物车中的产品”文本在不刷新页面的情况下更改,只有按钮样式中断。
-
我已经回答了您商店和存档页面上的 JQuery 部分……检查一下。请不要忘记为这个有用的帖子Relabel "add to cart" button after add to cart in WooCommerce点赞。
标签: php wordpress woocommerce product cart