WooCommerce Cart Count, Dynamic tag for Bricks Builder

it is what it is

it ca nbe very usefull for conditions and interactions …etc

{wc_cart_count}




// 1. Add a new dynamic tag 'wc_cart_count' to the Bricks Builder dynamic tags list.
add_filter( 'bricks/dynamic_tags_list', 'add_wc_cart_count_tag_to_builder' );
function add_wc_cart_count_tag_to_builder( $tags ) {
    $tags[] = [
        'name'  => 'wc_cart_count',
        'label' => 'WooCommerce Cart Count',
        'group' => 'WooCommerce',
    ];

    return $tags;
}

// 2. Helper function to get the total number of items currently in the WooCommerce cart.
function get_woocommerce_cart_count() {
    // Check if WooCommerce is active and cart is available.
    if ( function_exists( 'WC' ) && WC()->cart ) {
        return WC()->cart->get_cart_contents_count();
    }

    // Return 0 if WooCommerce or cart isn't available.
    return 0;
}

// 3. Render the 'wc_cart_count' dynamic tag by returning the cart count.
add_filter( 'bricks/dynamic_data/render_tag', 'render_wc_cart_count_tag', 10, 3 );
function render_wc_cart_count_tag( $tag, $post, $context = 'text' ) {
    if ( $tag === 'wc_cart_count' ) {
        return get_woocommerce_cart_count();
    }
    return $tag;
}

// 4. (Optional) If you want to replace a placeholder in your content with the cart count.
add_filter( 'bricks/dynamic_data/render_content', 'render_wc_cart_count_in_content', 10, 3 );
function render_wc_cart_count_in_content( $content, $post, $context = 'text' ) {
    if ( strpos( $content, '{wc_cart_count}' ) !== false ) {
        $count   = get_woocommerce_cart_count();
        $content = str_replace( '{wc_cart_count}', $count, $content );
    }
    return $content;
}