首页 > 解决方案 > 更新自定义元数据的 WP 产品查询达到内存限制

问题描述

服务器的内存限制约为 2000mb。这是相当高的,所以我不确定简单地增加这个限制是否是答案。

该脚本用于get_posts遍历所有 100,000 多个产品,get_the_terms以获取一个属性,其中最大的一个是update_post_meta更新元字段。

该脚本的主要原因是根据使用高级自定义字段转发器的订单集为产品分配自定义元“priority_brand”。这样,某人可以按品牌顺序拖放优先级,然后在前端我修改其他地方的查询以根据该优先级顺序显示这些产品。

以下脚本作为 CRON 运行:

<?php
include '/path/to/wp-load.php';

echo "brand-priority";
error_log("brand-priority");


$brands = get_field("brands_order", "options");
$brand_IDs = array();
foreach ($brands as $brand) {
  array_push($brand_IDs, $brand['brand']);
}

$args = array(
  'post_type' => 'product',
  'posts_per_page' => -1,
  'fields' => 'ids',
);
$products = get_posts($args);

$i = 1; foreach ($products as $ID) {
  $brand = get_the_terms($ID, 'pa_brand');
  $brand = $brand[0] ?? false;
  if (!$brand) {
    continue;
  }

  $brand_ID = $brand->term_id;
  $priority = array_search($brand_ID, $brand_IDs) + 1;

  update_post_meta($ID, "priority_brand", $priority);
}

我不确定我还能如何优化这个脚本。我已经只返回要迭代的 ID。我相信最大的问题是update_post_meta功能,但我不知道如何才能更优化地更新元数据。

更新:我wp_suspend_cache_addition( true );在脚本顶部添加(在error_log之后)。同样的问题仍然存在。

标签: phpwordpresswoocommerceadvanced-custom-fields

解决方案


推荐阅读