CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools
  • Angular
  • Web Development
    • React & TypeScript
    • Node.js
    • PHP & MySQL
  • Tech & AI News
  • Tools & Plugins
  • About
  • Contact Us
HomeWeb Development Block Bindings API in WordPress Plugins: PHP Sources, Editor UI & Batched Loops

Block Bindings API in WordPress Plugins: PHP Sources, Editor UI & Batched Loops

Anil Mehra on December 2, 2026
Web Development Wordpress Plugins
WordPress Block Bindings API guide banner showing custom PHP sources connected to Gutenberg block editor Attributes sidebar
7 Min Read

In a WooCommerce and SaaS billing plugin I maintained last year, six custom React blocks existed just to print a price, a seat quota, and an SLA badge, while our first naive rollout of the Block Bindings API spiked a 24-card Query Loop from 18ms to 290ms TTFB because every card fired its own SQL query. Pairing server-side batching with client-side getFieldsList() dropdowns let me delete 1,800 lines of React block code and cut archive render time back down to 18ms.

Most tutorials stop after registering a toy PHP callback on init. However, shipping that half-built pattern forces your editors into the raw Code Editor just to bind a paragraph. Below, I’ll walk through the dual PHP and JavaScript architecture I now ship in production alongside clean WordPress autoloaded options hygiene so your plugin stays fast and editable.

Why Custom Dynamic Blocks Lose to the Block Bindings API

Custom Gutenberg blocks carry hidden maintenance debt. Every time WordPress updates typography controls, spacing presets, or theme.json fluid scaling, you have to audit your custom edit.js markup so it doesn’t break block validation. Instead, binding dynamic plugin fields directly onto core Paragraph, Heading, Image, and Button blocks inherits every core design tool for free.

There’s a second safety win too. When a site owner temporarily disables a plugin that registers custom blocks, the page falls back to ugly raw HTML comments or broken editor warnings. By contrast, a bound core Paragraph block still renders clean fallback text cleanly because the block itself belongs to WordPress core.

Registering a Batched PHP Source in the Block Bindings API

Here’s the database trap I hit on my first production deployment. Inside a 24-item Query Loop, WordPress invokes your get_value_callback once per bound block attribute, which means three bound fields per card can trigger 72 separate database lookups unless you batch them. Therefore, I preload visible post IDs into a static PHP map before reading a single field:

<?php
declare(strict_types=1);

namespace CoreGamix\PlanPricing;

final class PlanBindingsSource {
    private static array $cache = [];

    public static function register(): void {
        if (!function_exists('register_block_bindings_source')) {
            return;
        }

        register_block_bindings_source(
            'coregamix/plan-pricing',
            [
                'label'              => __('Plan Pricing', 'coregamix-pricing'),
                'get_value_callback' => [self::class, 'getValue'],
                'uses_context'       => ['postId', 'postType'],
            ]
        );

        // Allow bindings on a custom badge block attribute in WordPress 6.9+.
        add_filter(
            'block_bindings_supported_attributes_coregamix/tier-badge',
            static fn(array $attrs): array => array_unique([...$attrs, 'label'])
        );
    }

    public static function warmPostIds(array $postIds): void {
        global $wpdb;
        $missing = array_values(array_diff(array_map('intval', $postIds), array_keys(self::$cache)));
        if ($missing === []) {
            return;
        }

        $placeholders = implode(',', array_fill(0, count($missing), '%d'));
        $table        = $wpdb->prefix . 'cgx_plan_tiers';
        $rows         = $wpdb->get_results(
            $wpdb->prepare("SELECT post_id, monthly_price, seat_limit, sla_tier FROM {$table} WHERE post_id IN ({$placeholders})", ...$missing),
            ARRAY_A
        );

        foreach ($missing as $id) {
            self::$cache[$id] = null;
        }
        foreach ($rows ?: [] as $row) {
            self::$cache[(int) $row['post_id']] = $row;
        }
    }

    public static function getValue(array $sourceArgs, \WP_Block $blockInstance, string $attributeName): ?string {
        $postId = (int) ($blockInstance->context['postId'] ?? get_the_ID());
        $field  = sanitize_key($sourceArgs['field'] ?? '');
        $allow  = ['monthly_price', 'seat_limit', 'sla_tier'];

        if ($postId <= 0 || !in_array($field, $allow, true)) {
            return null;
        }

        if (!array_key_exists($postId, self::$cache)) {
            global $wp_query;
            $loopIds = wp_list_pluck($wp_query->posts ?? [], 'ID');
            self::warmPostIds($loopIds ?: [$postId]);
        }

        $row = self::$cache[$postId] ?? null;
        if ($row === null) {
            return null;
        }

        return match ($field) {
            'monthly_price' => sprintf('$%d / month', (int) $row['monthly_price']),
            'seat_limit'    => sprintf('Up to %d Seats', (int) $row['seat_limit']),
            'sla_tier'      => esc_html((string) $row['sla_tier']),
            default         => null,
        };
    }
}

add_action('init', [PlanBindingsSource::class, 'register']);

Notice two deliberate details in that class. First, passing uses_context with postId and postType guarantees your callback resolves the current card inside a Query Loop rather than the parent page ID. Second, hooking the WordPress 6.9+ block_bindings_supported_attributes filter lets your own custom blocks participate without duplicating binding logic, as documented in the official WordPress developer reference for block bindings.

Block Bindings API architecture diagram illustrating PHP server source registration, Editor JS source, metadata bindings bridge, and batched SQL lookup
Dual PHP and JavaScript registration flow feeding core Gutenberg blocks with batched Query Loop lookups instead of N+1 SQL queries.

That static warmup cuts database round-trips aggressively. For example, on a catalog archive rendering 24 pricing cards, my Query Monitor trace dropped from 24 individual SELECT calls (290ms TTFB) to one indexed IN (...) lookup completing in 18ms. Similarly, if your plugin paginates thousands of rows inside a custom table, pair this pattern with MySQL keyset pagination so deep archive pages never stall on offset scans.

Exposing Custom Fields in the Attributes Sidebar UI

Editors hate editing JSON inside HTML comments. Even so, many plugin authors forget to mirror their PHP source on the client side, which leaves the Gutenberg Inspector blank. Instead, calling registerBlockBindingsSource() from @wordpress/blocks with getFieldsList() populates a native dropdown inside the sidebar Attributes panel:

import { registerBlockBindingsSource } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';

interface PricingArgs {
  field?: 'monthly_price' | 'seat_limit' | 'sla_tier';
}

const EDITOR_PREVIEW_LABELS: Record<string, string> = {
  monthly_price: '$149 / month',
  seat_limit: 'Up to 50 Seats',
  sla_tier: '99.95% Priority SLA',
};

registerBlockBindingsSource({
  name: 'coregamix/plan-pricing',
  label: __('Plan Pricing', 'coregamix-pricing'),
  usesContext: ['postId', 'postType'],
  getFieldsList() {
    return [
      {
        label: __('Monthly Price', 'coregamix-pricing'),
        type: 'string',
        args: { field: 'monthly_price' },
      },
      {
        label: __('Included Seats', 'coregamix-pricing'),
        type: 'string',
        args: { field: 'seat_limit' },
      },
      {
        label: __('Support SLA Tier', 'coregamix-pricing'),
        type: 'string',
        args: { field: 'sla_tier' },
      },
    ];
  },
  getValues({ bindings }) {
    const resolved: Record<string, string> = {};
    for (const [attrName, binding] of Object.entries(bindings)) {
      const args = (binding.args ?? {}) as PricingArgs;
      const key = args.field ?? 'monthly_price';
      resolved[attrName] = EDITOR_PREVIEW_LABELS[key] ?? __('Unbound field', 'coregamix-pricing');
    }
    return resolved;
  },
  canUserEditValue() {
    return false;
  },
});
WordPress Gutenberg Block Editor Attributes inspector sidebar binding a core Paragraph block to a custom plugin Block Bindings source
Visualizing the Gutenberg Block Editor Attributes sidebar panel connecting a core Paragraph block to a custom plugin binding source without writing a custom block.

Once I enqueued that tiny TypeScript module on enqueue_block_editor_assets, support tickets from our marketing team dropped to zero. Because canUserEditValue() returns false for billing fields synced from Stripe, editors can bind pricing cards visually without accidentally typing conflicting numbers into the canvas. You can also wire setValues() to write back to post meta when fields should stay editable, following the WordPress Developer Blog editor bindings guide.

Inspecting Serialized Metadata in Block Patterns

Check the saved markup once before shipping your block patterns. When a user picks Monthly Price from the Attributes dropdown, WordPress writes a compact JSON object into the core block delimiter:

<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"coregamix/plan-pricing","args":{"field":"monthly_price"}}}}} -->
<p>Contact sales for current tier pricing.</p>
<!-- /wp:paragraph -->

That fallback string inside the <p> tag matters. If your custom table ever returns null for a draft plan, WordPress leaves the fallback copy intact instead of outputting an empty box. Also, when you bind core/image URLs dynamically in product cards, make sure uploaded assets are already compressed with tools like our Media Condenser WordPress image optimizer so dynamic hero swaps never hurt LCP.

Block Bindings API vs Custom Blocks vs Shortcodes

Choosing the right rendering primitive saves months of refactoring later. Therefore, I evaluate every new plugin feature against these five criteria before writing a single JSX file:

DimensionBlock Bindings APICustom Dynamic BlockLegacy Shortcode
Core Styling & theme.jsonInherited automaticallyManual supports & CSSMinimal theme styling
Editor Canvas PreviewLive via getValues()Full custom React UIRaw bracket text only
Plugin Deactivation FallbackClean core block HTMLBroken block commentVisible raw [tag] text
Complex InteractivityNot designed for formsFull JS / Interactivity APIManual enqueue scripts
Best Production FitPrices, badges, meta, CTAsCalculators, sliders, tablesLegacy theme compat only

In short, use the Block Bindings API whenever you are projecting server-side strings, URLs, or alt text into standard layout primitives. On the other hand, keep custom dynamic blocks for multi-step calculators, interactive filters, or bespoke DOM widgets that core blocks can’t represent cleanly.

Common Developer Questions on Custom Bindings

Can the Block Bindings API bind attributes on custom third-party blocks?

Yes, starting in WordPress 6.9 you can opt custom blocks into the binding pipeline using the block_bindings_supported_attributes filter or its block-specific variant. Simply append your target attribute names in PHP and ensure those attributes map cleanly to HTML markup during server rendering.

Why doesn’t my custom binding source show up in the Gutenberg Attributes panel?

Registering a source in PHP only powers frontend rendering and REST responses. Because the Block Editor inspector reads client-side metadata, you must also call registerBlockBindingsSource() in JavaScript with getFieldsList() and enqueue that script with the wp-blocks dependency.

Anil Mehra on December 2, 2026 Web Development Wordpress Plugins
previous article

Leave a comment Cancel reply

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

About the Author

Anil Mehra

Anil Mehra

Software Engineer · Google AI Certified

Anil Mehra is a Software Engineer specializing in Angular (NgRx, SignalStore, RxJS), React, TypeScript, Node.js, PHP, and MySQL. Holding the Google AI Professional Certificate, he bridges production web architecture with practical AI-powered workflows.

Google AI Professional Certificate official badge

Google AI Professional Certificate

Google · Coursera Credential ↗

About & Consulting · Instagram · LinkedIn

Recent Guides

  • WordPress Block Bindings API guide banner showing custom PHP sources connected to Gutenberg block editor Attributes sidebar
    Block Bindings API in WordPress Plugins: PHP Sources, Editor UI & Batched LoopsDecember 2, 2026
  • WordPress autoloaded options architecture card showing wp_options payload reduction from 1.84 MB to 186 KB and TTFB drop
    WordPress Autoloaded Options: Fix Plugin Bloat, TTFB Spikes & Cache EvictionsDecember 2, 2026
  • claude sonnet 4.5 retirement migration guide banner
    Claude Sonnet 4.5 Retirement Hits Today: How I Migrated Node.js Calls to Sonnet 5.5November 30, 2026
  • speculation rules api instant prerender LCP guide banner
    Speculation Rules API Guide: Cut Route LCP to 38ms Without Phantom AnalyticsNovember 30, 2026

Engineering Topics

  • Angular 13
  • Frontend Development 4
  • Node.js 3
  • PHP & MySQL 2
  • React & TypeScript 2
  • SEO & Performance 2
  • Tech & AI News 4
  • Web Development 21
  • Wordpress Plugins 3
CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools

contact

support@coregamix.com

© 2026 CoreGamix. All Rights Reserved.  |  About  |  Privacy Policy  |  Terms of Use  |  Contact

Back to top