【问题标题】:Update wordpress Advance custom field on 40,000 existing posts更新 40,000 个现有帖子的 wordpress 高级自定义字段
【发布时间】:2019-06-21 11:44:29
【问题描述】:

我的网站上有 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' );

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

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

谢谢

【问题讨论】:

  • 如果这是问题,您可以只运行前 10000 个代码并检查。然后使用偏移量跳过这些帖子。
  • @Chilll007 感谢您的回复,我的PHP技术不强,您可以用您的偏移代码更新原始帖子中的代码吗?
  • 你也可以为它创建一个 AJAX 调用,这样它就可以一次运行 1 个或 100 个,直到它完成。

标签: wordpress advanced-custom-fields


【解决方案1】:

你可以试试下面的代码。

$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 个帖子

【讨论】:

  • @chill007 会更新前 10000 个帖子吗?如果是,那么我尝试运行包含 100 个帖子的代码并随机检查一些开始的帖子,但它没有更新它们。
  • 是的,它会更新这些帖子。也许你的代码有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 2016-06-25
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多