如果选择了WordPress Gutenberg块样式,则可程序性地添加额外的类。

问题描述 投票:0回答:1

在使用WordPress Gutenberg区块时,我已经为现有的区块添加了自定义样式--例如,区块引号的盒装版--使用了 滤波器 (register_block_style()). 这是整洁的,因为它让编辑者在没有编程知识的情况下点击可视化编辑器,这秘密地增加了自定义类。

然而,我有一个依赖性:如果这个类的 is-style-box-quote 已增加。small-content-width 也必须存在。

有什么办法可以在程序上添加吗?也许在保存帖子的时候?我应该用哪个钩子过滤器来实现?


(经过一番研究和尝试)

如果我得到我想编辑的部分通过 save_post() (然后是$post['post_content'])我得到一个很长的HTML字符串。像这样。

[…]
<!-- wp:quote {"className":"is-style-box-quote"} -->
<blockquote class="wp-block-quote is-style-box-quote"><p>Lorem ipsum dolor sit amet.</p></blockquote>
<!-- /wp:quote -->
[…]

通过regex来修改是可能的,但是很麻烦。有没有一种既定的比较好的方法来更新DB中的类?

wordpress wordpress-gutenberg programmatically wordpress-hook
1个回答
0
投票

我没有看到一个blockquote块,所以我猜测它是一个自定义块。下面的例子是一个引用块。

import { assign } from 'lodash';

addFilter(
    'blocks.getSaveContent.extraProps',
    'core/quote',
    ( props ) => {

        if( props.className.contains( 'is-style-large' ) )
        {
            assign( props, { className : props.className + " small-content-width" } );
        }
    }
);

这里是过滤器的文档。https:/developer.wordpress.orgblock-editordevelopersfiltersblock-filters#blocks-getsavecontent-extraprops。

我建议做的是不要编辑现有的样式,而是添加自己的自定义块样式。这样的话,默认的样式就会保持原来的样子。

import { registerBlockType } from '@wordpress/blocks';
import { domReady} from '@wordpress/dom-ready';

domReady( () => {
    registerBlockStyle( 'core/quote', [ 
            {
                name: 'my-custom-block-style',
                label: 'The label',
            }
        ]);
    } );
} );

这里是在现有区块上添加自己的区块样式的文档。https:/developer.wordpress.orgblock-editordevelopersfiltersblock-filters#block-style-variations。

© www.soinside.com 2019 - 2024. All rights reserved.