You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP 8.0下自定义订单状态出现Attempt to read property "ID"警告的修复方法

修复PHP 8.0中WooCommerce自定义订单状态的"Attempt to read property 'ID' on null"警告

问题原因

升级到PHP 8.0后,代码里的if( get_post_type($post->ID) != 'shop_order' ) return; // Exit触发警告,核心原因是PHP 8.0对null对象访问属性的校验更严格:当$post全局变量未初始化(比如在edit.php页面但未加载具体订单时),直接调用$post->ID会抛出警告,而PHP 7.4会静默忽略这类错误。

另外注意:代码开头独立于函数外的那行if( get_post_type($post->ID) != 'shop_order' ) return;没有实际作用,还会提前触发报错,建议直接删除。

修复方案

方案1:先校验$post是否存在

修改styling_packed_order_list函数中的判断逻辑,先确认$post不为null,再执行类型判断:

add_action('admin_head', 'styling_packed_order_list' );
function styling_packed_order_list() {
    global $pagenow, $post;

    if( $pagenow != 'edit.php') return; // Exit
    // 先检查$post是否存在,再判断文章类型
    if( !$post || get_post_type($post->ID) != 'shop_order' ) return; // Exit

    // HERE below set your custom status
    $order_status = 'packed'; // <==== HERE
    ?>
    <style>
        .order-status.status-<?php echo sanitize_title( $order_status ); ?> {
            background: #0D98BA;
            color: #ffffff;
        }
    </style>
    <?php
}

方案2:通过页面查询参数判断(更可靠)

直接利用edit.php页面的post_type GET参数判断当前是否为订单列表,无需依赖$post变量:

add_action('admin_head', 'styling_packed_order_list' );
function styling_packed_order_list() {
    global $pagenow;

    if( $pagenow != 'edit.php') return; // Exit
    // 通过URL参数直接判断当前页面的文章类型
    if( isset($_GET['post_type']) && $_GET['post_type'] != 'shop_order' ) return; // Exit

    // HERE below set your custom status
    $order_status = 'packed'; // <==== HERE
    ?>
    <style>
        .order-status.status-<?php echo sanitize_title( $order_status ); ?> {
            background: #0D98BA;
            color: #ffffff;
        }
    </style>
    <?php
}

内容的提问来源于stack exchange,提问作者roadlink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:15:46