首页 > 解决方案 > 结帐后更新 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);

标签: wordpresswoocommercealgolia

解决方案


您可能错过了您链接到的文档页面中示例代码的最后一行:

add_action('update_post_meta', 'algolia_update_post_meta', 10, 4);

这位于您的之外algolia_update_post_meta,将让 Wordpress/WooCommerce 知道algolia_update_post_meta无论何时调用该update_post_meta操作都必须调用 。

这个动作将由 Wordpressupdate_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);


推荐阅读