sourcecode

wc_get_products()의 결과를 json 인코딩할 수 없습니다.

copyscript 2023. 10. 21. 10:40
반응형

wc_get_products()의 결과를 json 인코딩할 수 없습니다.

저는 다음 코드를 사용하여 베스트셀러 제품을 받아 JSON으로 결과를 보내고 있습니다.그러나 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 );

wc_get_products ()은(는) 보호된 데이터가 포함된 개체 배열을 반환합니다.

Array
(
    [0] => WC_Product_Simple Object
        (
            [data:protected] => values
            .
            .
            .
        )
    [1] => WC_Product_Variable Object
        (
            [data: protected] => values
            .
            .
            .
        )
    [2]
    .
    .
    .
)

그러나 wc_json_encode()는 이러한 보호된 데이터를 인코딩할 수 없습니다.

그래서 아래와 같은 작업을 해야 json의 모든 데이터를 얻을 수 있습니다.

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

$products_data = wc_get_products( $best_selling_args );

$simplified_data = array();

foreach ($products_data as $key => $single_product_data) {
    $simplified_data[$key] = $single_product_data->get_data();
}

echo '<pre>';
print_r( wp_json_encode( $simplified_data ) );
echo '</pre>';

언급URL : https://stackoverflow.com/questions/53496680/unable-to-json-encode-the-result-of-wc-get-products

반응형