php 在自定义帖子加载之前更新 meta字段值,然后显示具有更新元值的帖子

rqenqsqc  于 2022-12-10  发布在  PHP
关注(0)|答案(1)|浏览(122)

我想做的是
我目前正在研究一种当用户进入产品页面时更新产品价格的方法。我正在使用API来获得准确的价格。

问题是

该函数正确地更新了后端的 meta字段sellers,但即使刷新后,元字段的值也不会显示在前端。我必须在后端手动更新帖子,以使元字段sellers在刷新页面时显示在前端。
我所做的一切
我设法处理了API请求,然后解析了响应。我还设法触发了API请求,并在必要时使用add_action钩子在我的产品页面的 meta字段中修改了价格。我目前使用的是send_headers钩子,它可能不是一个合适的钩子,但至少它有点工作:p
代码

add_action( 'send_headers', 'fetch_seller_price' );

function fetch_seller_price(){
    
    //check if is front
    if ( !is_admin() ) {
        $post_id = get_the_ID();
        
        //Check if is custom post type
        if ('bons-plans' == get_post_type( $post_id )) {
            
            //Get ASIN code from custom meta field
            $asin_code = get_post_meta( $post_id, 'asin_code', true );

            //check if product code is correct
            if (strlen( $asin_code ) == 10) {
                
                $sellers = get_post_meta($post_id, 'sellers', true);

                foreach ($sellers as $item => $value) {
                    
                    //Check if seller is Amazon
                    if ($value["seller"] == "Amazon") {
                        
                        //get price from api function
                        $item_price = amazon_price_request( $asin_code );
                        //If new price != old price, update sellers array with new product price value 
                        if ($value["product-price"] != $item_price) {
                            $sellers[$item]["product-price"] = $item_price;
                            
                        }
                    }
                
                update_post_meta( $post_id, "sellers", $sellers );
                
                }
            }
        }
    }
    
}

注意:sellers meta字段是一个嵌套数组,它包含多个seller数组,其形式为:

["item-2"]=>
  array(9) {
    ["seller"]=>
    string(6) "Amazon"
    ["product-link"]=>
    string(23) "https://amzn.to/3E90AFS"
    ["product-price"]=>
    string(2) "42"
    }

我在前面加载页面后尝试了var_dump()sellers数组,也尝试了item_price变量。两者都返回了正确的数字,但最终结果显示为空。
任何帮助将不胜感激!
我对PHP有点陌生,我很清楚我的代码有点垃圾,任何关于如何使它正确的想法也是可以接受的:p

bf1o4zei

bf1o4zei1#

好的,问题是我解析json响应的方式,变量是float,而预期的格式是string:p

相关问题