WordPress.org

WordPress Developer Blog

Snippet: How to filter the output of a block binding

Snippet: How to filter the output of a block binding

WordPress Block Bindings API provides a powerful way to connect block content with dynamic data sources. While bindings themselves are useful, sometimes you need to modify their output. Using the block_bindings_source_value filter, you can transform the data before it’s displayed on the front end.

Consider a scenario where you have a custom post type called book and need to store the price for each book as post meta. The price will be stored in US dollars, but you want to give users the ability to view prices in different currencies. By adding a query parameter to the URL (like ?currency=EUR), users can dynamically switch between US dollars, Euros, and British pounds. Let’s walk through how to implement this using block bindings.

First, register the post meta using register_post_meta() to make it available to blocks in the Editor:

add_action( 'init', function() {
    register_post_meta(
        'book',
        'book_price',
        array(
            'show_in_rest'      => true,
            'single'            => true,
            'type'              => 'string',
            'label'             => __( 'Book Price', 'text-domain' ),
            'description'       => __( 'Book price in USD', 'text-domain' ),
            'sanitize_callback' => 'wp_strip_all_tags',
        )
    );
} );

Next, you can use the block_bindings_source_value filter to intercept the price value when it’s displayed and convert it based on a query parameter. For instance, a URL with ?currency=GBP will automatically display the price in British pounds. The binding can be added to any block that supports content, like a Paragraph block, using the core/post-meta source.

add_filter( 'block_bindings_source_value', function( $value, $source, $args ) {
    // Only process if the source and key are correct.
    if ( 'core/post-meta' !== $source || 'book_price' !== $args['key'] ) {
        return $value;
    }

    // Get currency from query parameter (e.g., ?currency=EUR).
    $currency = isset( $_GET['currency'] ) ? sanitize_text_field( wp_unslash( $_GET['currency'] ) ) : 'USD';
    
    // Base price in USD.
    $price = floatval( $value );
    
    // Conversion rates (you might want to use a real API for live rates).
    $conversion_rates = array(
        'EUR' => 0.92, // 1 USD = 0.92 EUR
        'GBP' => 0.79, // 1 USD = 0.79 GBP
        'USD' => 1.00,
    );
    
    // Convert price.
    $converted_price = $price * ( isset( $conversion_rates[ $currency ] ) ? $conversion_rates[ $currency ] : 1 );
    
    // Format price with currency symbol.
    $currency_symbols = array(
        'EUR' => '€',
        'GBP' => '£',
        'USD' => '$',
    );
    
    $symbol = isset( $currency_symbols[ $currency ] ) ? $currency_symbols[ $currency ] : '$';
    
    // Format the price with 2 decimal places.
    return sprintf( '%s%.2f', $symbol, $converted_price );
}, 10, 3 );

Here’s a quick demonstration of how to use this new functionality:

This approach gives you a flexible way to modify block binding output based on user input or other parameters. While this example uses hardcoded conversion rates, you could easily extend it to use a currency conversion API for live rates.

If you are interested in learning more about the Block Bindings API, here are several articles to get you started:

Props to @greenshady, @welcher, and @santosguillamot for reviewing this post.

One response to “Snippet: How to filter the output of a block binding”

  1. Kadim Gültekin Avatar

    Thank you so much, this is exactly what I was looking for…

Leave a Reply

Your email address will not be published. Required fields are marked *