php - wc_get_products 返回空数组?
问题描述
我制作了一个插件,因此我可以拥有自定义端点。最终,我想提取有关我的可预订产品(woocommerce 预订)的数据。
这是我的插件:
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins',
get_option( 'active_plugins' ) ) ) ) {
// Define constants.
define( 'CUSTOM_ENDPOINTS_PLUGIN_VERSION', '1.0.0' );
define( 'CUSTOM_ENDPOINTS_PLUGIN_DIR', __FILE__ );
// Include the main class.
require plugin_dir_path( __FILE__ ) . '/class-rest-custom-woocommerce-endpoints.php';
}
然后在我的主类文件中:
add_action( 'woocommerce_loaded', 'get_data');
add_action( 'rest_api_init', 'custom_endpoint_first');
function custom_endpoint_first(){
register_rest_route( 'cwe/v1/booking', '/get-data',
array(
'methods' => 'GET',
'callback' => 'get_data')
);
}
function get_data() {
$args = array( 'include' => array(28));
$products = wc_get_products( $args );
return $products;
}
我不知道为什么它返回一个空数组,但是当我调用我的自定义 URL 时它有 200 个状态。
解决方案
使用此代码段以 JSON 格式获取产品。
public function get_products()
{
$p = wc_get_products(array('status' => 'publish'));
$products = array();
foreach ($p as $product) {
$products[] = $product->get_data();
}
return new WP_REST_Response($products, 200);
}
推荐阅读
- django - 这两种在 Django 中提供静态文件的方法有什么区别?
- firebase - 在 Firebase 中添加自定义 Oauth2 提供程序
- sql - 从多对多表中添加总计和存在聚合的高效 SQL 查询
- git - 在推送更改时创建重复文件
- c# - 等级增加时如何产生障碍物?
- xcode - '无法启动 iphonesimulator 的模拟器 .. 无法启动模拟器 '
- javascript - 按唯一子元素查找父元素,但单击另一个子元素
- reactjs - 如何在我的浅层测试中定义匹配路由器道具
- python - TensorFlow 中的学习率衰减 - 分段常量函数出错
- node.js - 如何将我的 api 数据链接存储到我的 MongoDB?