woocommerce offtopic - Unable to enocde the result of wc_get_products

admin2025-06-06  7

I am using the following code to get the best selling products and send the result in JSON. But I am unable to encode the result of wc_get_products().

    $best_selling_args = array(
        'meta_key' => 'total_sales', 
        'order'    => 'DESC',
        'orderby'  => 'meta_value_num'
     );

    $products_posts = wc_get_products( $best_selling_args );

//  var_dump( $products_posts );

    echo wp_json_encode( $products_posts );

I am using the following code to get the best selling products and send the result in JSON. But I am unable to encode the result of wc_get_products().

    $best_selling_args = array(
        'meta_key' => 'total_sales', 
        'order'    => 'DESC',
        'orderby'  => 'meta_value_num'
     );

    $products_posts = wc_get_products( $best_selling_args );

//  var_dump( $products_posts );

    echo wp_json_encode( $products_posts );
Share Improve this question asked Nov 27, 2018 at 9:34 Sagar Bahadur TamangSagar Bahadur Tamang 1331 silver badge10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default -1

Try:

$products_posts_arr = (array) $products_posts;
echo json_encode( $products_posts_arr );

OR

function object_to_array($data) {
    if (is_array($data) || is_object($data)) {
        $result = array();
        foreach ($data as $key => $value) {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

$products_posts_arr = object_to_array( $products_posts );
echo json_encode( $products_posts_arr );

Encode array not object, wc_get_products will return object.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749149054a316783.html

最新回复(0)