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

WordPress页面出现Trying to get property 'name' of non-object错误求助

解决WordPress "Trying to get property 'name' of non-object" 错误

错误原因

这个警告的核心问题是$post_type_obj并非有效对象——get_post_type_object(get_post_type())在某些场景下会返回false或null(比如代码在文章循环外执行、当前无有效Post对象,或者传入了不存在的文章类型),此时直接访问->name或->has_archive就会触发报错。

修复方案

在访问$post_type_obj的属性前,先做有效性判断,确保它是一个对象。修复后的代码如下:

$post_type = get_post_type();
$post_type_obj = $post_type ? get_post_type_object($post_type) : false;
$time_string = '';

// 先确认$post_type_obj是有效对象,再判断属性
if ($post_type_obj && ('post' === $post_type_obj->name || $post_type_obj->has_archive)) {
    $time_string = '<time class="published updated date_single" datetime="%1$s">%2$s</time>';
    if (get_the_time('U') !== get_the_modified_time('U')) {
        $time_string = '<time class="published date_single" datetime="%1$s">%2$s</time>';
    }
    $time_string = sprintf(
        $time_string,
        esc_attr(get_the_date('c')),
        esc_html(get_the_date()),
        esc_attr(get_the_modified_date('c')),
        esc_html(get_the_modified_date()),
    );
    $time_string = '<a class="" href="' . esc_url(get_permalink()) . '" rel="bookmark">' . $time_string . '</a>'; 
}

关键修复点

  • 先获取$post_type并检查是否有效,再传入get_post_type_object
  • 在if判断的最前面增加$post_type_obj的有效性检查,确保后续属性访问安全
  • 保留原有业务逻辑的同时,避免了非对象属性访问的警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:01:37