【问题标题】:wc_get_products returns empty array?wc_get_products 返回空数组?
【发布时间】:2019-07-05 11:06:57
【问题描述】:

我制作了一个插件,因此我可以拥有自定义端点。最终,我想提取有关我的可预订产品(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 个状态。

【问题讨论】:

    标签: php wordpress woocommerce woocommerce-rest-api


    【解决方案1】:

    使用这个 sn-p 获取 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);
    }
    

    【讨论】:

      【解决方案2】:

      这一行

      'include' => array(28)

      表示您只会获得 id 为 28 的产品。
      该产品存在吗?
      这是你的意图吗?

      如果没有,请查看此链接以获取一些示例
      https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#usage

      【讨论】:

      • 嘿!是的,这个产品理想地存在,我只想拉出我所有的产品,但我只是为了测试,因为前者仍然给我一个空数组。
      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2021-08-11
      • 2017-02-27
      • 2020-04-01
      • 2019-04-17
      • 2017-04-24
      • 2019-09-13
      相关资源
      最近更新 更多