Hello developers. I have created a dynamic data using AI to display the number of items in the cart and it works fine. I wanted to share it to make sure it is correct and written correctly.
I hope to have this dynamic data natively in Bricks in the near future.
add_filter('bricks/dynamic_tags_list', function($tags) {
$tags[] = [
'name' => '{cart_count}',
'label' => 'Cart Count',
'group' => 'custom',
];
return $tags;
});
add_filter('bricks/dynamic_data/render_tag', function($tag) {
if ($tag !== '{cart_count}') return $tag;
$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
return '<span data-brx-cart-count="bfzuxu">' . $count . '</span>';
}, 20, 3);
$render_cb = function($content) {
if (strpos($content, '{cart_count}') === false) return $content;
$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
return str_replace('{cart_count}', '<span data-brx-cart-count="bfzuxu">' . $count . '</span>', $content);
};
add_filter('bricks/dynamic_data/render_content', $render_cb, 20, 3);
add_filter('bricks/frontend/render_data', $render_cb, 20, 2);
add_filter('woocommerce_add_to_cart_fragments', function($fragments) {
$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
$fragments['span[data-brx-cart-count="bfzuxu"]'] = '<span data-brx-cart-count="bfzuxu">' . $count . '</span>';
return $fragments;
});
add_action('wp_footer', function() {
if (!is_cart()) return;
?>
<script>
(function($){
function updateCartCount() {
$.post('<?php echo admin_url('admin-ajax.php'); ?>', {action:'get_cart_count'}, function(count){
$('span[data-brx-cart-count="bfzuxu"]').html(count);
});
}
$(document.body).on('updated_cart_totals removed_from_cart wc_cart_emptied', updateCartCount);
})(jQuery);
</script>
<?php
});
add_action('wp_ajax_get_cart_count', function() {
wp_send_json(WC()->cart ? WC()->cart->get_cart_contents_count() : 0);
});
add_action('wp_ajax_nopriv_get_cart_count', function() {
wp_send_json(WC()->cart ? WC()->cart->get_cart_contents_count() : 0);
});