更新40,000个现有帖子上的wordpress Advance自定义字段

时间:2019-01-28 12:58:50

标签: wordpress advanced-custom-fields

我的网站上有40000个帖子。昨天,我使用默认值创建了一个新的高级自定义字段。当我打开任何现有帖子时,不会显示默认值,但是当我单击“更新”按钮或创建新帖子时,会显示默认值。

我在线找到了一个脚本,用于放入function.php文件,该文件会自动更新值。脚本是

add_action('admin_init', 'set_default_acf_values');

function set_default_acf_values() {

$args = [
    'post_type'      => 'chemicals',
    'posts_per_page' => -1,
];

   $posts = get_posts($args);

   foreach($posts as $post) 
    {
         if (empty(get_field('stock_1', $post->ID))) {
         update_field('stock_1', DEFAULT_AD_LINK, $post->ID);
    }





}
}

但是,当我运行脚本时,它显示了内存错误。

Your PHP code changes were rolled back due to an error on line 916 of file wp-includes/meta.php. Please fix and try saving again.

Allowed memory size of 805306368 bytes exhausted (tried to allocate 20480 bytes)

我相信它显示内存错误的原因是因为帖子过多。

我还增加了wp-config.php文件中的内存限制,但这根本没有帮助

define( 'WP_MEMORY_LIMIT', '256M' );

我正在寻找一种从现有帖子的NEW字段中获取默认值或更新所有现有帖子而又不会出现内存错误的方法。

任何帮助或指针将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码。

$args = [
    'post_type'      => 'chemicals',
    'posts_per_page' => 10000,
];

   $posts = get_posts($args);

   foreach($posts as $post) 
    {
         if (empty(get_field('stock_1', $post->ID))) {
         update_field('stock_1', DEFAULT_AD_LINK, $post->ID);
    }

之后,您可以使用

$args = [
        'post_type'      => 'chemicals',
        'offset'  => 10000,
        'posts_per_page' => 10000,
    ];

       $posts = get_posts($args);

       foreach($posts as $post) 
        {
             if (empty(get_field('stock_1', $post->ID))) {
             update_field('stock_1', DEFAULT_AD_LINK, $post->ID);
        }

它将给您下一个从10001开始的10000帖子