Wordpress/WC - 在页面加载前更新 Post/Product 元数据
Wordpress/WC - Update Post/Product Meta Before Page loads
我正在尝试在我的 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
}
因此,当加载产品页面时,这会正确更改产品的库存量。问题是,此更改未反映为页面 loaded/rendered。必须刷新或重新访问该页面才能显示新的库存量。我也曾尝试使用 'init' 挂钩和 'template_redirect' 挂钩,但这些不允许我访问产品以获取 id/sku/other 信息以发送到 API 用于数据检索。
有谁知道我可以获取产品的详细信息、更新 post 元数据(我正在使用 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);
}
}
感谢这位用户就类似问题提供的信息:
我正在尝试在我的 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
}
因此,当加载产品页面时,这会正确更改产品的库存量。问题是,此更改未反映为页面 loaded/rendered。必须刷新或重新访问该页面才能显示新的库存量。我也曾尝试使用 'init' 挂钩和 'template_redirect' 挂钩,但这些不允许我访问产品以获取 id/sku/other 信息以发送到 API 用于数据检索。
有谁知道我可以获取产品的详细信息、更新 post 元数据(我正在使用 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);
}
}
感谢这位用户就类似问题提供的信息: