我正在创建一个插件,以将wordpress多站点帖子从一个站点克隆到网络中的另一个站点。
到目前为止,这是我的代码
我只加载帖子ID,而不是整个帖子。
看着分析器,执行脚本时内存使用量继续增加,最终导致max_memory错误
class Cloner {
private $types = [];
public $total_posts = 0;
public $transfer_to;
function __construct($post_types = null, $transfer_to) {
$this->types = $this->get_registered_post_types();
$this->transfer_to = $transfer_to;
foreach ($this->types as $key => $type) {
$this->do_transfer_for_post_type($type);
}
}
function do_transfer_for_post_type($type) {
$posts = $this->get_post_ids_for_transfer($type);
$type_count = count($posts);
$this->total_posts = $this->total_posts + $type_count;
$this->transfer($posts);
unset ($posts);
}
function get_post_ids_for_transfer($post_type) {
// only get ids to save memory
$args = array(
'posts_per_page' => -1,
'post_type' => $post_type,
'fields' => 'ids',
'no_found_rows' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'cache_results' => false
);
$q = new WP_Query($args);
$posts = $q->posts;
wp_reset_query();
return $posts;
}
function transfer($posts) {
foreach ($posts as $id) {
$this->copy_post_to_blog($id);
}
}
function copy_post_to_blog($post_id) {
$post = get_post($post_id, ARRAY_A); // get the original post
$meta = get_post_meta($post_id);
$post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post
switch_to_blog($this->transfer_to); // switch to target blog
$inserted_post_id = wp_insert_post($post); // insert the post
$this->insert_meta($meta, $inserted_post_id);
$post = null;
restore_current_blog(); // return to original blog
}
function insert_meta($meta, $post_id) {
global $wpdb;
$custom_fields = [];
$query_string = "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value) VALUES ";
foreach($meta as $key => $value) {
array_push($custom_fields, $post_id, $key, $value[0]);
$place_holders[] = "('%d', '%s', '%s')";
}
$query_string .= implode(', ', $place_holders);
$query = $wpdb->prepare("$query_string ", $custom_fields);
$wpdb->query( $query );
}
function get_registered_post_types() {
$args = array(
'public' => true,
'_builtin' => false,
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
return get_post_types( $args, $output, $operator );
}
}
$cloner = new Cloner(null, 7);
我希望脚本使用相当一致的内存量-如何清理它?