You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

插件激活创建页面后,如何将短码放入Gutenberg HTML块而非经典编辑器

解决插件激活创建页面时,短码显示在Gutenberg HTML块的问题

嘿,我来帮你搞定这个问题!你现在遇到的情况是:用wp_insert_post直接写入短码时,WordPress会默认把内容按经典编辑器的格式存储,而Gutenberg编辑器需要的是块结构的特殊注释格式,所以得把短码包装成Gutenberg HTML块的结构才行。

问题根源

Gutenberg编辑器的内容是用特殊的注释标签来标记不同块的,纯文本的短码会被识别为经典编辑器的内容,而不是Gutenberg的HTML块。

修改后的代码

直接上能解决问题的代码,我把关键部分改好了:

register_activation_hook( __FILE__, 'my_plugin_install_function');
function my_plugin_install_function() {
    // 构建Gutenberg HTML块的内容格式
    $gutenberg_html_block = '<!-- wp:html -->
[customization-shortcode]
<!-- /wp:html -->';

    // post status and options
    $post = array(
        'comment_status' => 'closed',
        'ping_status' => 'closed' ,
        'post_author' => get_current_user_id(),
        'post_date' => date('Y-m-d H:i:s'),
        'post_name' => 'Checklists',
        'post_status' => 'publish' ,
        'post_content' => $gutenberg_html_block, // 这里用块结构的内容
        'post_title' => 'Checklists',
        'post_type' => 'dash',
    );

    // insert page and save the id
    $newvalue = wp_insert_post( $post, false );

    // save the id in the database
    update_option( 'hclpage', $newvalue );
}

额外注意点

  • 确保你的自定义文章类型dash是支持Gutenberg编辑器的:在注册这个post type的时候,supports参数里要包含'editor',比如:

    register_post_type( 'dash', array(
        // 其他参数...
        'supports' => array( 'title', 'editor', 'thumbnail' ),
    ) );
    

    如果之前没加'editor',即使内容是块格式,页面可能还是会用经典编辑器打开。

  • 这段代码里的HTML块注释是Gutenberg官方的格式,WordPress会自动识别这个注释,把里面的短码渲染成HTML块。

这样修改后,插件激活创建的页面打开时,短码就会在Gutenberg的HTML块里,而不是经典编辑器啦!

内容的提问来源于stack exchange,提问作者Nash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:24:57