将快捷代码批量转换为带嵌入的块

时间:2021-10-08 作者:Grant Barrett

有没有办法将短代码嵌入大规模转换为古腾堡块样式嵌入,包括将经典块转换为古腾堡块?

我正在移动一个WordPress网站,这个网站的主题已经十年没有更新了。它有数千个音频文件,其中嵌入了一个SoundCloud短代码,看起来像这样:

[soundcloud url="http://api.soundcloud.com/tracks/11111111" params="auto_play=false&show_artwork=false&color=ff7700" width="100%" height="180" iframe="true" /]

但是,为了使它们能够自动与屏幕播放器配合使用,屏幕播放器在滚动时在页面底部显示音频文件,需要将它们转换为块样式嵌入:

<figure class="wp-block-embed is-type-rich is-provider-soundcloud wp-block-embed-soundcloud"><div class="wp-block-embed__wrapper">http://api.soundcloud.com/tracks/11111111</div></figure>

对数据库进行regex搜索并更改这些内容非常简单。

然而,旧的短代码在经典块中,如果这些经典块在regex搜索和替换之前没有转换为Gutenberg块,那么WordPress不会将新替换的文本视为正确的块样式嵌入。它只是将它们视为无意义的代码,而不进行解释。

所以问题是,有没有办法将经典积木大规模转换为古腾堡积木?我已经在WordPress商店中看到并尝试了所有声称可以做到这一点的插件,但它们已经不起作用了,而且它们在评论中提供的解决方案也不起作用。我还查看了他们的代码,以确定我是否可以让他们工作,但这超出了我的技能水平。

1 个回复
SO网友:Grant Barrett

最终,我通过从数据库导出wp\\u posts表并按照以下行进行正则表达式搜索,解决了这个问题

\'([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\', \'[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9])\', \'(.*?)\\[soundcloud url=\\\\"http://api\\.soundcloud\\.com/tracks/(.*?)\\\\" params=\\\\"auto_play=false&show_artwork=false&color=ff7700&show_playcount=false\\\\" width=\\\\"100%\\\\" height=\\\\"180\\\\" iframe=\\\\"true\\\\" /]

并将其替换为

\'\\1\', \'<!-- wp:paragraph -->\\2<!-- /wp:paragraph --><!-- wp:embed \\{"url":"http://api.soundcloud\\.com/tracks/\\3","type":"rich","providerNameSlug":"soundcloud","responsive":true\\} --> <figure class="wp-block-embed is-type-rich is-provider-soundcloud wp-block-embed-soundcloud"><div class="wp-block-embed__wrapper"> http://api\\.soundcloud\\.com/tracks/\\3 </div></figure> <!-- /wp:embed -->

尽管这成功地将每一篇文章(超过5000篇)转换为两个古腾堡区块,WordPress认为段落区块已损坏,需要恢复。为了解决这个问题,我在Github上找到了一条评论Javascript code for the edit admin page 当一篇文章被打开进行编辑时,这将默默地恢复所有可能损坏的块。我在这里包括代码(credit to AjXUthaya) 以防注释消失。

管理js公司:

import autoRecoverBlocks from \'./wordpress/autoRecoverBlocks\';

// DECONSTRUCT: WP
const { wp = {} } = window || {};
const { domReady, data } = wp;

// AWAIT: jQuery to get ready
jQuery(document).ready(function ($) {
  // DEFINE: Validation variables
  const hasGutenbergClasses = $(\'body\').hasClass(\'post-php\') === true && $(\'.block-editor\').length >= 1;
  const gutenbergHasObject = domReady !== undefined && data !== undefined;
  const gutenbergIsPresent = hasGutenbergClasses === true && gutenbergHasObject === true;

  // IF: Gutenberg editor is present
  if (gutenbergIsPresent === true) {
    autoRecoverBlocks(false);
  }
});
自动恢复锁定。js公司:

// FUNCTION: Recover block
const recoverBlock = (block = null, autoSave = false) => {
  // DECONSTRUCT: WP object
  const { wp = {} } = window || {};
  const { data = {}, blocks = {} } = wp;
  const { dispatch, select } = data;
  const { createBlock } = blocks;
  const { replaceBlock } = dispatch(\'core/block-editor\');
  const wpRecoverBlock = ({ name = \'\', attributes = {}, innerBlocks = [] }) => createBlock(name, attributes, innerBlocks);

  // DEFINE: Validation variables
  const blockIsValid = block !== null
    && typeof block === \'object\'
    && block.clientId !== null
    && typeof block.clientId === \'string\';

  // IF: Block is not valid
  if (blockIsValid !== true) {
    return false;
  }

  // GET: Block based on ID, to make sure it exists
  const currentBlock = select(\'core/block-editor\').getBlock(block.clientId);

  // IF: Block was found
  if (!currentBlock !== true) {
    // DECONSTRUCT: Block
    const {
      clientId: blockId = \'\',
      isValid: blockIsValid = true,
      innerBlocks: blockInnerBlocks = [],
    } = currentBlock;

    // DEFINE: Validation variables
    const blockInnerBlocksHasLength = blockInnerBlocks !== null
      && Array.isArray(blockInnerBlocks)
      && blockInnerBlocks.length >= 1;

    // IF: Block is not valid
    if (blockIsValid !== true) {
      // DEFINE: New recovered block
      const recoveredBlock = wpRecoverBlock(currentBlock);

      // REPLACE: Broke block
      replaceBlock(blockId, recoveredBlock);

      // IF: Auto save post
      if (autoSave === true) {
        wp.data.dispatch("core/editor").savePost();
      }
    }

    // IF: Inner blocks has length
    if (blockInnerBlocksHasLength) {
      blockInnerBlocks.forEach((innerBlock = {}) => {
        recoverBlock(innerBlock, autoSave);
      })
    }
  }

  // RETURN
  return false;
};

// FUNCTION: Attempt to recover broken blocks
const autoRecoverBlocks = (autoSave = false) => {
  // DECONSTRUCT: WP object
  const { wp = {} } = window || {};
  const { domReady, data = {} } = wp;
  const { select } = data;

  // AWAIT: For dom to get ready
  domReady(function () {
    setTimeout(
      function () {
        // DEFINE: Basic variables
        const blocksArray = select(\'core/block-editor\').getBlocks();
        const blocksArrayHasLength = Array.isArray(blocksArray)
          && blocksArray.length >= 1;

        // IF: Blocks array has length
        if (blocksArrayHasLength === true) {
          blocksArray.forEach((element = {}) => {
            recoverBlock(element, autoSave);
          });
        }
      },
      1
    )
  });
}

// EXPORT
export default autoRecoverBlocks;
要使用Javascript,请将这两个部分另存为两个文件。将它们放在服务器上激活模板目录中的/js/目录中。然后在模板的函数中添加排队函数。php文件。我的代码很简单:

function add_script_to_menu_page()
{
    // $pagenow, is a global variable referring to the filename of the current page, 
    // such as ‘admin.php’, ‘post-new.php’
    global $pagenow;
 
    if ($pagenow != \'post.php\') {
        return;
    }
     
    // loading js
    wp_register_script( \'autoRecoverBlocks\', get_template_directory_uri().\'/js/autoRecoverBlocks.js\', array(\'jquery-core\'), false, true );
    wp_enqueue_script( \'autoRecoverBlocks\' );
}
 
add_action( \'admin_enqueue_scripts\', \'add_script_to_menu_page\' );
此外,对于没有断块但我确实希望将经典块转换为Gutenberg块的页面,我安装了Convert to Blocks 插件,它在保存帖子时以静默方式进行转换。

相关推荐

列出短码(DO_SHORTCODE)中的分类术语段

我想在我的短代码中列出分类术语。这是我获取术语列表的方式(用逗号分隔):<?php $terms = get_the_terms( $post->ID , array( \'shoptype\' ) ); $i = 1; foreach ( $terms as $term ) { $term_link = get_term_link( $ter