WordPress导入CSV时如何将HTML内容转换为区块编辑器格式?
用PHP将HTML转WordPress区块编辑器代码,及CSV导入同步转换
一、PHP完全能实现HTML转区块格式
当然可以用PHP搞定,不用依赖JS。WordPress区块编辑器(Gutenberg)的内容是块注释标记+对应HTML的组合格式,比如标题块用<!-- wp:heading {"level":2} -->包裹<h2>内容,段落块用<!-- wp:paragraph -->包裹<p>,我们只要解析HTML标签,替换成对应的块结构就行。
基础实现代码
下面是针对你提供的示例HTML写的转换函数,能处理标题、段落、图片标签:
function html_to_gutenberg_blocks($html) { // 转换h1-h6标题为区块 $html = preg_replace_callback('/<h([1-6])(.*?)>(.*?)<\/h\1>/si', function($matches) { $level = $matches[1]; $content = trim($matches[3]); return sprintf('<!-- wp:heading {"level":%d} --><h%d%s>%s</h%d><!-- /wp:heading -->', $level, $level, $matches[2], $content, $level); }, $html); // 转换段落为区块 $html = preg_replace_callback('/<p(.*?)>(.*?)<\/p>/si', function($matches) { $content = trim($matches[2]); if (empty($content)) return ''; $class_attr = !empty($matches[1]) ? '{"className":"'.strip_tags($matches[1]).'"}' : ''; return sprintf('<!-- wp:paragraph %s --><p%s>%s</p><!-- /wp:paragraph -->', $class_attr, $matches[1], $content); }, $html); // 转换图片为区块 $html = preg_replace_callback('/<img(.*?)src="(.*?)"(.*?)alt="(.*?)"(.*?)width="(.*?)"(.*?)>/si', function($matches) { $src = esc_url($matches[2]); $alt = esc_attr($matches[4]); $width = esc_attr($matches[6]); return sprintf('<!-- wp:image {"width":%s} --><figure class="wp-block-image"><img src="%s" alt="%s" width="%s"/></figure><!-- /wp:image -->', $width, $src, $alt, $width); }, $html); // 清理多余空行 $html = preg_replace('/\n\s*\n/', "\n\n", $html); return $html; } // 测试示例HTML $sample_html = '<h2>The apple tree (Malus pumila, commonly and erroneously called Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple. </h2> <p>It is cultivated worldwide as a fruit tree, and is the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe, and were brought to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek and European Christian traditions.</p> <img src="http://localhost/demo/wp-content/uploads/2023/02/16764902337724-16764902303769-swan-7606921__340.jpg" alt="apple" width="300px"> <p>Apple trees are large if grown from seed. Generally apple varieties are propagated by grafting onto rootstocks, which control the size of the resulting tree. There are more than 7,500 known cultivars of apples, resulting in a range of desired characteristics. Different cultivars are bred for various tastes and uses, including cooking, eating raw and cider production. Trees and fruit are prone to a number of fungal, bacterial and pest problems, which can be controlled by a number of organic and non-organic means. In 2010, the fruit\'s genome was sequenced as part of research on disease control and selective breeding in apple production.</p>'; // 输出转换后的区块内容 echo html_to_gutenberg_blocks($sample_html);
运行后会把你的示例HTML转换成标准的Gutenberg块格式,比如标题会变成:
<!-- wp:heading {"level":2} --><h2>The apple tree (Malus pumila, commonly and erroneously called Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple. </h2><!-- /wp:heading -->
二、CSV导入时同步完成转换
完全可以,分两种场景处理:
1. 用第三方插件(比如WP All Import)
在插件设置里:
- 先把上面的
html_to_gutenberg_blocks函数添加到插件的「自定义代码」区域 - 映射CSV的内容字段时,直接用
[html_to_gutenberg_blocks({你的内容列名})]作为内容值,插件会自动把CSV里的HTML转成块格式再导入。
2. 自定义PHP导入脚本
自己写脚本的话,逻辑就是读取CSV每一行,先转HTML为块格式,再插入到WordPress:
// 先确保在WordPress环境下运行(比如开头引入wp-load.php) require_once('/path/to/your/wp-load.php'); // 读取CSV文件 $csv_file = fopen('your-posts.csv', 'r'); $header = fgetcsv($csv_file); // 循环处理每一行数据 while (($row = fgetcsv($csv_file)) !== FALSE) { $post_data = array_combine($header, $row); // 转换HTML内容为区块格式 $block_content = html_to_gutenberg_blocks($post_data['content']); // 插入文章到WordPress wp_insert_post([ 'post_title' => $post_data['title'], 'post_content' => $block_content, 'post_status' => 'publish', 'post_type' => 'post' ]); } fclose($csv_file);
三、注意点
- 上面的代码是基础版,要是需要处理列表、引用、代码块等更多标签,扩展正则匹配规则就行;复杂嵌套结构可以用PHP的
DOMDocument类解析,比正则更靠谱。 - 图片块可以根据需求加对齐、链接到媒体文件等属性,调整块的JSON配置就行。
内容的提问来源于stack exchange,提问作者iamavijitdas
相关产品推荐
相关产品推荐

