首页 > 解决方案 > Wordpress/WC - 在页面加载之前更新帖子/产品元数据

问题描述

我正在尝试在我的 WooCommerce 商店中创建功能,以在单击项目时更新它们的库存数量/他们的产品页面是基于外部数据库和 API 加载的。我已经使用这样的钩子成功地创建了函数:

add_action('woocommerce_before_single_product', 'update_product_stock');
function update_product_stock(){
  global $product;
  $sku = $product -> get_sku();
  //code for updating based on $sku
}

因此,当产品页面加载时,这会正确更改产品的库存量。问题是,当页面被加载/渲染时,这种变化没有反映出来。必须刷新或重新访问页面才能显示新的库存数量。我也尝试使用“init”钩子和“template_redirect”钩子,但这些不允许我访问产品以获取 id/sku/其他信息以发送到 API 以进行数据检索。

有谁知道我获取产品项目详细信息、更新帖子元数据(我正在使用 wc_update_product_stock())并将这些更改反映在页面视图上而无需重新加载的方法?我想我最终还必须在搜索结果页面上实现它,但我想先对其进行排序。

标签: phpwordpresshookaction

解决方案


如果其他人最终需要类似的东西,我最终能够获得我将在这里演示的所需功能。

//this hook runs before the page/product loop
add_action('storefront_before_site', 'update_product_stock');

function update_product_stock(){
  //since this now runs before the standard post loop,
  //need a different way to access the post.
  //use page id to differentiate between products and other shop pages.
  $page_id = get_queried_object_id();

  //my code for fetching stock here
  $stock_num_to_set = determine_new_stock();

  $product = new WC_Product($page_id);

  //check that the page is indeed a product page 
  //(i use the sku, use your own preferred method)
  $product_sku = get_post_meta($page_id, '_sku', true);

  if($product_sku){
    //update using woocommerce product update.
    //now this is the info that will be fetched as the post is loaded normally
    wc_update_product_stock($product, $stock_num_to_set);
  }
}

感谢这位用户就类似问题提供的信息:https ://stackoverflow.com/a/3127776/6581190


推荐阅读