Order properties should not be accessed directly

This code:

    foreach ($order-meta_data as $row) {
        if ($row-key == 'tid') {
            $tid = $row-value;
            break;
        }
    }

within the function

function function_name($order_id, $checkout = null) {
        global $woocommerce;
        $order = new WC_Order($order_id);
        foreach ($order-meta_data as $row) {
            if ($row-key == 'tid') {
                $tid = $row-value;
                break;
            }
        }
    if (!empty($tid)) {
        ...
    }
}

add_action('woocommerce_order_status_changed', 'function_name');

triggers the PHP notice "Order properties should not be accessed directly" and I don't know what's the problem. I run Woocommerce 3.0.8 and Wordpress 4.8. Is it a bug or I do some mistake?

Update:

Fixed code looks like this:

foreach ($order-get_meta_data() as $row) {
    if ($row-key === 'tid') {
        $tid = $row-value;
        break;
    }
}

Or even better:

$tid = $order-get_meta($key = 'tid');

More info from Woocommerce docs.

Topic woocommerce-offtopic plugin-development customization Wordpress

Category Web


It means you shouldn't access $order->meta_data (and other properties) directly, but use the provided getter and setter functions.

In this case, use $order->get_meta_data().

This method is (eventually) inherited from the WC_Data class.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.