首页 > 解决方案 > 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 个状态。

标签: phpwordpresswoocommercewoocommerce-rest-api

解决方案


使用此代码段以 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);
}

推荐阅读