【问题标题】:Wordpress/WC - Update Post/Product Meta Before Page loadsWordpress/WC - 在页面加载之前更新帖子/产品元数据
【发布时间】:2019-04-15 08:17:55
【问题描述】:

我正在尝试在我的 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())以及无需重新加载即可将这些更改反映在页面视图上的方法?我想我最终也必须在搜索结果页面上实现这一点,但我想先对其进行排序。

【问题讨论】:

    标签: php wordpress hook action


    【解决方案1】:

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

    //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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多