无法对 wc_get_products() 的结果进行 json 编码

Sag*_*ang 6 wordpress json woocommerce

我使用以下代码来获取最畅销的产品并以 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 );
Run Code Online (Sandbox Code Playgroud)

Yas*_*ash 1

wc_get_products() 返回其中包含受保护数据的对象数组,例如

Array
(
    [0] => WC_Product_Simple Object
        (
            [data:protected] => values
            .
            .
            .
        )
    [1] => WC_Product_Variable Object
        (
            [data: protected] => values
            .
            .
            .
        )
    [2]
    .
    .
    .
)
Run Code Online (Sandbox Code Playgroud)

但 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>';
Run Code Online (Sandbox Code Playgroud)