【发布时间】:2021-03-28 18:37:30
【问题描述】:
我目前正在将 90K+ 帖子导入自定义帖子类型,包括分类法和元值。由于我遇到了几个问题和疑问,我想问问社区是否有人有导入这么多帖子的经验。
我阅读了多篇关于这个主题的帖子,但我不能 100% 确定我是否找到了好的解决方案。我目前对导入功能的设置是这样的:
function import() {
global $wpdb;
if (!defined('WP_IMPORTING')) {
define('WP_IMPORTING', true);
}
ini_set("memory_limit", -1);
set_time_limit(0);
ignore_user_abort(true);
wp_defer_term_counting(true);
wp_defer_comment_counting(true);
$wpdb->query('SET autocommit = 0;');
// register a function for execution on shutdown
register_shutdown_function(function () {
global $wpdb;
$wpdb->query('COMMIT;');
$wpdb->query('SET autocommit = 1;');
wp_defer_term_counting(false);
wp_defer_comment_counting(false);
});
foreach($x as $y => $z) {
// check if current already exists
$postExists = post_exists(…);
if (!is_wp_error($postExists)) {
$postId = wp_insert_post(…);
// taxonomies
if (isset(…)) {
$term = term_exists(…);
if($term) {
wp_set_post_terms(…);
}
}
// meta values
// do one query for multiple meta values
$metaKeys = [];
$metaKeys['key'] = 'value';
…
$customFields = [];
$placeHodlers = [];
$queryString = "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value) VALUES ";
foreach ($metaKeys as $key => $value) {
array_push($customFields, $postId, $key, $value);
$placeHodlers[] = "('%d', '%s', '%s')";
}
$queryString .= implode(', ', $placeHodlers);
$wpdb->query($wpdb->prepare("$queryString ", $customFields));
}
}
$wpdb->query('COMMIT;');
$wpdb->query('SET autocommit = 1;');
wp_defer_term_counting(false);
wp_defer_comment_counting(false);
}
由于无休止的处理,导入仍然经常失败。
谢谢!
【问题讨论】:
-
我的经验是将它们批量化,您可以将它们分成 1,000 个组并多次处理。这样你就不会给服务器带来压力。还有其他并发方法(后台进程、cron、队列),但取决于您的控制和 exp 做块可能是最好的方法