Woocommerce get_products return empty objects

妖精的绣舞 提交于 2021-02-11 17:42:20

问题


I'm building custom endpoint using Woocommerce Products and the query return 6 objects but empty don't now why is that? what I'm missing on my code below?

Code

add_action('rest_api_init', function () {

         register_rest_route( 'hash', 'related-products',array(
                 'methods' => 'GET',
                 'callback' => 'hash_realated_products'
         ));
});

function hash_realated_products() {
    // Get 10 most recent product IDs in date descending order.
    $query = new WC_Product_Query( array(
                                         'limit' => 6,
                                         'status' => 'publish',
                                         'orderby' => 'rand',
                                         'tax_query' => array(
                                                              'taxonomy' => 'product_cat',
                                                              'field'    => 'term_id',
                                                              'terms'     =>  '257,352'                                                              'operator'  => 'IN'
                                                              )

                                         ) );
    $products = $query->get_products();
    return $products;

}


回答1:


The problem was I didn't call for the data from the products array!

so the final code will be :

$products_query = $query->get_products();
$products = array();
foreach ( $products_query as $product ) {

    $products[] = $product->get_data();
}

return $products;


来源:https://stackoverflow.com/questions/59361618/woocommerce-get-products-return-empty-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!