admin管理员组

文章数量:1125596

I am making an override to core/image block -disabling styles, changing markup and such.

I have managed to solve some things, but struggle with some others.

Here is my code:

filters.php

<?php

use MyTheme\PictureGenerator;

add_filter(
    'render_block',
    function ( $block_content, $block ) {
        if ('core/image' !== $block['blockName']) return $block_content;

        if (array_key_exists('id', $block['attrs'])) {
            $caption       = array_key_exists('caption', $block['attrs']) ? $block['attrs']['caption'] : '';
            $block_content = PictureGenerator::get_picture_html($block['attrs']['id'], '', 2048, 2048, $caption);
        }

        return $block_content;
    },
    10,
    2
);

It turned out, that caption is not available in $block['attrs']['caption']. What is the expected way to obtain it? Preg_matching $block['innerHtml'] seems like an overkill for me.

hooks.js

import { Fragment } from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';

const blockSettings = function ( settings, name ) {
    if ( name !== 'core/image' ) {
        return settings;
    }

    const { styles, ...otherSettings } = settings;
    settings = Object.assign( otherSettings );

    return settings;
};

const blockControls = createHigherOrderComponent( ( BlockEdit ) => {
    return ( props ) => {
        const { name } = props;

        // Check if it's the 'core/image' block
        if ( name !== 'core/image' ) {
            return <BlockEdit { ...props } />;
        }

        return (
            <>
                <BlockEdit { ...props } />
                { /* You can add additional components or controls here if needed */ }
            </>
        );
    };
}, 'blockControls' );


wp.hooks.addFilter( 'blocks.registerBlockType', 'mytheme/image', blockSettings );

wp.hooks.addFilter( 'editor.BlockEdit', 'mytheme/image', blockControls );

As for the js side, how do I access and modify caption onChange to for example save it to another custom attribute? Is this a good solution to save it as string to custom attribute?

本文标签: filtersCoreImage access caption in rendertemplate and in wphooks