Make WordPress Core


Ignore:
Timestamp:
02/13/2024 03:10:21 PM (3 months ago)
Author:
Bernhard Reiter
Message:

Block Hooks: Set ignoredHookedBlocks metadata upon saving.

Decouple hooked blocks insertion from setting the metadata.ignoredHookedBlocks attribute on anchor blocks, and perform the latter step upon saving a template or template part to the database. This ensures that anchor blocks that have been newly added to a template (or part) on the client side will also get ignoredHookedBlocks metadata set correctly, thus preserving editor/front-end parity. Hooked block insertion, on the other hand, will continue to happen upon reading a template (or part).

Props gziolo, tomjcafferkey.
Fixes #60506.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/block-template-utils.php

    r57594 r57627  
    14331433    return $template_hierarchy;
    14341434}
     1435/**
     1436 * Inject ignoredHookedBlocks metadata attributes into a template or template part.
     1437 *
     1438 * Given a `wp_template` or `wp_template_part` post object, locate all blocks that have
     1439 * hooked blocks, and inject a `metadata.ignoredHookedBlocks` attribute into the anchor
     1440 * blocks to reflect the latter.
     1441 *
     1442 * @param WP_Post $post A post object with post type set to `wp_template` or `wp_template_part`.
     1443 * @return WP_Post The updated post object.
     1444 */
     1445function inject_ignored_hooked_blocks_metadata_attributes( $post ) {
     1446    $hooked_blocks = get_hooked_blocks();
     1447    if ( empty( $hooked_blocks ) && ! has_filter( 'hooked_block_types' ) ) {
     1448        return;
     1449    }
     1450
     1451    // At this point, the post has already been created.
     1452    // We need to build the corresponding `WP_Block_Template` object as context argument for the visitor.
     1453    // To that end, we need to suppress hooked blocks from getting inserted into the template.
     1454    add_filter( 'hooked_block_types', '__return_empty_array', 99999, 0 );
     1455    $template = _build_block_template_result_from_post( $post );
     1456    remove_filter( 'hooked_block_types', '__return_empty_array', 99999 );
     1457
     1458    $before_block_visitor = make_before_block_visitor( $hooked_blocks, $template, 'set_ignored_hooked_blocks_metadata' );
     1459    $after_block_visitor  = make_after_block_visitor( $hooked_blocks, $template, 'set_ignored_hooked_blocks_metadata' );
     1460
     1461    $blocks  = parse_blocks( $template->content );
     1462    $content = traverse_and_serialize_blocks( $blocks, $before_block_visitor, $after_block_visitor );
     1463
     1464    wp_update_post(
     1465        array(
     1466            'ID'            => $post->ID,
     1467            'post_content'  => $content,
     1468        )
     1469    );
     1470}
Note: See TracChangeset for help on using the changeset viewer.