首页 > 解决方案 > Woocommerce Rest APi 获取自定义元字段

问题描述

我正在尝试使用其余 api 从 woocommerce 中提取产品自定义元和自定义分类值。但无论我尝试什么似乎都无法让它工作。不知道我错过了什么。

例如,我的产品有一个自定义元值“product_location”。帖子元值存在并且有效,因为我可以使用它来将值拉入 woocommerce 产品页面:

get_post_meta($product->get_id(), 'product_location', true );

在我的 functions.php 文件中,我添加了:

add_action( 'rest_api_init', 'handle_location' );

function handle_location() {
    register_rest_field( 'post', 'product_location', array(
        'get_callback' => array( $this, 'get_the_product_location' ),
        'schema' => null
    ));        
}   

function get_the_product_location( $post, $field_name, $request ) { 
    return get_post_meta( $post[ 'id' ], $field_name, true );
}

但是,当我打电话说 https://*******.com/wc-api/v2/products/302341/ 时,元数据不包括在内。那么基本上我怎样才能包含额外的元数据呢?我也计划尝试将其用于自定义分类法。任何帮助表示赞赏 - 谢谢

标签: woocommercemetadatawordpress-rest-api

解决方案


尝试将您的底部功能更改为

  function get_the_product_location( $post, $field_name, $request ) { 
  return get_post_meta( $post[ 'id' ], 'product_location', $meta_value );
  }

推荐阅读