在深入搜索之后,我创建了一个WooCommerce短代码。这样做的目的是为了显示“购买X多产品以获得折扣”的信息。
我的代码:
add_shortcode('check', 'custommessage');
function custommessage() {
$items_count = WC()->cart->get_cart_contents_count();
$min_count = 6;
if( $items_count < $min_count ){
echo sprintf('%s products more for discount' , $min_count - $items_count );
}
}在WooComerce cart页面上,在将X产品添加到购物车或删除它工作的数量后,自动刷新消息
但是当我把短代码(放在边车上)时,它不会自动刷新X计数。尽管它也是AJAX驱动的。
有什么我能解决的建议吗?
发布于 2021-09-07 10:03:27
若要对消息进行公正处理,以便在添加/删除项时(通过ajax)进行更新,请使用woocommerce_add_to_cart_fragments筛选器钩子。
所以你得到了:
function custom_message() {
// Initialize
$message = __( 'Default message', 'woocommerce' );
// True
if ( WC()->cart ) {
// Get number of items in the cart.
$items_count = WC()->cart->get_cart_contents_count();
$min_count = 6;
if ( $items_count < $min_count ) {
$message = sprintf( __( '%s products more for discount', 'woocommerce' ), $min_count - $items_count );
} else {
$message = __( 'Some message', 'woocommerce' );
}
}
return $message;
}
// Refreshing on cart ajax events
function filter_woocommerce_add_to_cart_fragments( $fragments ) {
$fragments['div.display-message'] = '<div class="display-message">' . custom_message() . '</div>';
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1 );1)然后使用通过一个短代码显示这一点:
function display_my_message() {
return '<div class="display-message">' . custom_message() . '</div>';
}
// Register shortcode
add_shortcode( 'display_message', 'display_my_message' );短代码使用
在现有的一页中:
[display_message]
或者在PHP中:
echo do_shortcode("[display_message]");
或
2)通过显示消息--任何所需的钩子(在本例中,我显示了2个钩子。1在购物车页和1在单一产品页,适应您的需要)。使用:
// Display message via the desired hooks
function display_message() {
echo '<div class="display-message">' . custom_message() . '</div>';
}
add_action( 'woocommerce_before_shop_loop', 'display_message', 10, 0 );
add_action( 'woocommerce_before_add_to_cart_form', 'display_message', 10, 0 );https://stackoverflow.com/questions/69085650
复制相似问题