php - wc_get_products 返回空数组?

标签 php wordpress woocommerce woocommerce-rest-api

我做了一个插件,所以我可以有自定义端点。最终,我想提取有关我的可预订产品(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);
}

关于php - wc_get_products 返回空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54639296/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 如何更改 Woocommerce 存档页面中的产品循环参数?

MySQL 从 WooCommerce 订单获取 SKU

php - 更改 WooCommerce 中特定付款方式的结帐提交按钮文本

php - 自定义帖子类型的WordPress页面父级

php - Woocommerce 结帐 AJAX PHP

php 反序列化返回 false

php - 尝试导出图像时 file_put_contents() 发出错误

php - 使用 PHP 有条件地在 header 中记录值

php - 如何在 WordPress 中保存复选框元框?