wordpress - 结帐后更新 Algolia 索引中的产品库存
问题描述
一旦通过 woo commerce 下订单,我无法让 Algolia 重新索引产品库存水平。不确定我应该使用什么函数来触发 algolia_update_post_meta。任何帮助将不胜感激。
编辑:到目前为止我从:https ://www.algolia.com/doc/integration/wordpress/indexing/automatic-updates/?language=php
嘿@Olivier对不起,那是我的错,我确实在上面的粘贴中错过了它。
我还更新了上面的代码以包含一些其他细节。
所以首先我们获取产品元数据,以便 Algolia 知道要索引什么。
function add_product_shared_attributes( array $shared_attributes, WP_Post $post ) {
$product = wc_get_product( $post );
$shared_attributes['price'] = $product->get_price();
$shared_attributes['availability'] = $product->get_availability();
$shared_attributes['stock_status'] = $product->get_stock_status();
$shared_attributes['regular_price'] = $product->get_regular_price();
$shared_attributes['sale_price'] = $product->get_sale_price();
$shared_attributes['is_on_sale'] = $product->is_on_sale();
$shared_attributes['sku'] = $product->get_sku();
$shared_attributes['stock'] = $product->get_stock_quantity();
$shared_attributes['attributes'] = (array) $product->get_attributes();
return $shared_attributes;
}
add_filter( 'algolia_post_product_shared_attributes', 'add_product_shared_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_product_shared_attributes', 'add_product_shared_attributes', 10, 2 );
- 以上效果很好-那里没有问题。
然后我们尝试在下订单时更新库存元 Algolia 端。无论出于何种原因,这都不起作用,我很困惑?
function algolia_update_post_meta($meta_id, $object_id, $meta_key, $_meta_value) {
global $algolia;
$indexedMetaKeys = ['stock'];
if (in_array($meta_key, $indexedMetaKeys)) {
$index = $algolia->initIndex(
apply_filters('algolia_index_name', 'wp_posts_product')
);
$index->partialUpdateObject([
'objectID' => 'post#'.$object_id,
$meta_key => $_meta_value,
]);
}
}
add_action('update_post_meta', 'algolia_update_post_meta', 10, 4);
解决方案
您可能错过了您链接到的文档页面中示例代码的最后一行:
add_action('update_post_meta', 'algolia_update_post_meta', 10, 4);
这位于您的之外algolia_update_post_meta
,将让 Wordpress/WooCommerce 知道algolia_update_post_meta
无论何时调用该update_post_meta
操作都必须调用 。
这个动作将由 Wordpress从update_post_meta()
函数中调用(是的,同名),所以当更新帖子的元数据时。
因此,除非我自己错过了什么,否则您的代码只是缺少那一行:
function algolia_update_post_meta($meta_id, $object_id, $meta_key, $_meta_value) {
global $algolia;
$indexedMetaKeys = ['stock_quantity'];
if (in_array($meta_key, $indexedMetaKeys)) {
$index = $algolia->initIndex(
apply_filters('algolia_index_name', 'wp_posts_product')
);
$index->partialUpdateObject([
'objectID' => 'post#'.$object_id,
$meta_key => $_meta_value,
]);
}
}
add_action('update_post_meta', 'algolia_update_post_meta', 10, 4);
推荐阅读
- ruby - Populate a table in rails 5 using an array
- php - symfony 4 上传文件时出错
- c# - “FACT”这个词是什么意思?
- r - 直接从 R 在 H2O 模型中实施自定义停止指标以在训练期间进行优化
- barcode - Ionic 3 条码扫描是否支持 GS1-128 条码格式?
- php - Woocommerce 外部/附属产品 URL 中的自定义查询字符串
- kotlin - Kotlin 主构造函数调用辅助构造函数
- excel - Excel 嵌套的 IF 将 FALSE 值串在一起并呈现 #VALUE
- c - char 指针的内存分配
- python - 无法使用 ctype 在 python 中加载 .dll