php - 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())并将这些更改反映在页面视图上而无需重新加载的方法?我想我最终还必须在搜索结果页面上实现它,但我想先对其进行排序。
解决方案
如果其他人最终需要类似的东西,我最终能够获得我将在这里演示的所需功能。
//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
推荐阅读
- java - Java 8 函数 - 在执行给定 lambda 之前执行某些操作的“包装器”函数?
- material-design - 为什么 material-icons i 元素与相邻的输入元素重叠?
- javascript - 单个文件中的 JavaScript 命名空间模块 VS 导入/导出加载的模块(例如 requireJS、es6)
- ios - 为什么通过照片库启动 iOS App 不起作用?
- sql - SELECT 语句中的通配符“_”
- php - PHPMailer 向某些电子邮件地址发送重复的电子邮件
- node.js - 从命令行打开文件并知道用户何时关闭它
- php - 如何返回一个非常小的数字作为 floatval() 但不作为科学记数法并且不使用 sprintf 因为它返回一个字符串
- r - 在R中将因子日期时间列转换为POSIXct
- android - 如何识别安全元件?