如何用PHP从外部JSON导入WordPress文章并应用WPBakery模板
实现思路与代码示例
我之前刚好做过类似的WPBakery模板批量导入需求,分享一下我的实现步骤和代码片段,应该能帮你解决问题:
1. 解析WPBakery模板数据
首先你从wp_options拿到的wpb_js_templates是JSON格式的字符串,里面包含了所有保存的WPBakery模板信息。我们需要先解码它,然后找到目标模板的内容和自定义CSS:
// 从WP选项中获取WPBakery模板数据 $templates_json = get_option('wpb_js_templates'); $templates = json_decode($templates_json, true); // 替换成你要使用的模板名称 $target_template_name = '产品详情页模板'; $selected_template = null; // 遍历找到目标模板 foreach ($templates as $template) { if ($template['name'] === $target_template_name) { $selected_template = $template; break; } } if (!$selected_template) { die('未找到指定的WPBakery模板,请检查模板名称是否正确'); } // 提取模板核心内容(直接用于填充post_content) $template_shortcode = $selected_template['content']; // 提取模板关联的自定义CSS $template_custom_css = $selected_template['custom_css'];
2. 导入外部JSON并创建带模板的文章
接下来读取外部JSON数据,循环创建文章,并把WPBakery模板的shortcode写入post_content,同时将自定义CSS存入wp_postmeta:
// 读取外部JSON数据(如果是本地文件可以用文件路径替代URL) $external_posts_json = file_get_contents('https://your-external-source/posts-data.json'); $external_posts = json_decode($external_posts_json, true); if (empty($external_posts)) { die('未读取到有效的外部JSON数据'); } // 循环处理每一条外部数据 foreach ($external_posts as $ext_post) { // 准备文章基础数据 $post_args = [ 'post_title' => wp_strip_all_tags($ext_post['title']), // 清理标题中的HTML标签 'post_content' => $template_shortcode, // 直接使用WPBakery模板的shortcode 'post_status' => 'publish', // 可以改成draft或pending按需调整 'post_type' => 'post', // 若要创建页面则改为page,或自定义文章类型slug 'post_author' => get_current_user_id(), // 替换成固定作者ID也可以,比如1 ]; // 插入文章到wp_posts表 $new_post_id = wp_insert_post($post_args); // 检查文章是否创建成功 if ($new_post_id && !is_wp_error($new_post_id)) { // 如果模板有自定义CSS,写入postmeta if (!empty($template_custom_css)) { update_post_meta($new_post_id, '_wpb_shortcodes_custom_css', $template_custom_css); } // 可选:从外部JSON导入其他自定义字段 // 比如外部数据里有产品价格字段,就可以这样存 // if (isset($ext_post['price'])) { // update_post_meta($new_post_id, 'product_price', $ext_post['price']); // } echo "文章「{$ext_post['title']}」创建成功<br>"; } else { $error_msg = is_wp_error($new_post_id) ? $new_post_id->get_error_message() : '未知错误'; error_log("创建文章失败:{$ext_post['title']},错误信息:{$error_msg}"); echo "文章「{$ext_post['title']}」创建失败,请查看日志<br>"; } }
3. 额外注意事项
- 动态替换模板内容:如果需要把外部JSON的内容(比如文章正文、图片)插入到WPBakery模板里,可以在模板中设置占位符(比如
{{POST_CONTENT}}、{{FEATURED_IMAGE}}),然后用str_replace替换:$dynamic_content = str_replace('{{POST_CONTENT}}', $ext_post['content'], $template_shortcode); - 外部JSON读取问题:如果
file_get_contents无法获取外部URL,可以改用cURL实现,避免因PHP配置限制失败。 - 批量导入优化:如果数据量很大,建议分批处理(比如每50条为一批),并添加
sleep(1)避免服务器超时,或者使用WP的后台任务插件来异步处理。 - 数据备份:操作数据库前一定要备份
wp_posts和wp_postmeta表,避免数据丢失。
内容的提问来源于stack exchange,提问作者Cláudio Baima
相关产品推荐
相关产品推荐

