开启Debug模式后WordPress taxonomy.php报非对象属性获取通知
Hey there, let's work through fixing that PHP notice you're seeing. The error Trying to get property of non-object on line 3961 of wp-includes/taxonomy.php happens because when the code tries to access $ancestor_term->slug, the $ancestor_term variable isn't a valid term object—it's either false or a WP_Error instead.
Since you confirmed your taxonomy.php is the unmodified WordPress core file, the issue isn't with the core code itself. It's almost always tied to broken term data in your database or a conflict with a plugin/theme interfering with term retrieval. Here are actionable steps to fix it:
Check for invalid ancestor term IDs
The code is fetching ancestor terms for a specific term, but one of those ancestor IDs might point to a term that no longer exists (like a deleted term leftover from a failed import or accidental removal). You can:- Pinpoint which term is triggering the error—look for context in your
error_logor visit the taxonomy/term page that causes the notice to appear. - Use a database tool like phpMyAdmin to check the
wp_term_taxonomyandwp_termstables. Verify that all ancestor IDs linked to your problematic term correspond to existing entries inwp_terms. If you find invalid IDs, clean them up manually (make sure to back up your database first!).
- Pinpoint which term is triggering the error—look for context in your
Add a safety check via a filter (no core edits needed)
Instead of modifying the coretaxonomy.phpfile, use a WordPress filter to ensureget_term()returns a valid object. Add this code to your active theme'sfunctions.phpfile (or a custom plugin):add_filter('get_term', function($term, $term_id, $taxonomy) { // If the term is invalid or an error, return an empty object to avoid notices if (!is_object($term) || is_wp_error($term)) { return (object) ['slug' => '']; } return $term; }, 10, 3);This ensures
$ancestor_termalways has aslugproperty to access, stopping the notice from triggering.Run WordPress database repair
WordPress has a built-in tool to fix corrupted database tables. Enable it by adding this line to yourwp-config.phpfile:define('WP_ALLOW_REPAIR', true);Then visit
your-site-url/wp-admin/maint/repair.php, run the repair and optimize options. Once done, remove that line fromwp-config.phpto keep your site secure.Check for plugin/theme conflicts
Sometimes a third-party plugin or custom theme can disrupt term retrieval. Try:- Disabling all plugins temporarily. If the notice disappears, re-enable them one by one to find the culprit.
- Switching to a default WordPress theme (like Twenty Twenty-Four). If the notice goes away, your theme is the issue—reach out to the theme developer for a fix.
The core code assumes get_term() will always return a valid term object, but real-world scenarios like data corruption or plugin interference can break that assumption. The steps above should help you track down and fix the root cause.
内容的提问来源于stack exchange,提问作者Juan Andres

