Blog / WordPress/ WordPress Pages Not Displaying Content While Posts Work: Bug Fix Log

WordPress Pages Not Displaying Content While Posts Work: Bug Fix Log

wordpress 页面无法输出内容,而文章可以,bug排除记录

Problem Description

A WordPress site was functioning normally except for one issue: Pages (Page post type) were not displaying their main content. Upon inspecting the generated HTML source, it was found that the the_content() function in the page.php template was not outputting any content.

Investigation Approach

The problem was almost certainly caused by an error in a filter hooked to the_content. I recalled modifying the theme's source code earlier that day to implement an automatic replacement of image alt attributes based on post tags, aiming to improve image SEO. This custom code was precisely hooked to the the_content filter.

Analysis and Resolution

Reviewing the relevant code, I discovered an if statement that checked if a post had tags. If tags existed, it performed the replacement. However, the critical flaw was that if a post had no tags, the function did nothing and simply ended without returning the original content.

The key insight is that WordPress Pages, by default, do not have the Tag taxonomy (though this can be added via plugins or code). Therefore, when accessing a Page, my custom function's condition failed, and because it didn't return the $content variable, the the_content filter output nothing.

Solution

Add an else branch after the if block to ensure content is always returned.

else {
    return $content;
}

After adding this code, Page content displayed correctly again.

Key Takeaway

When writing code that modifies core WordPress filters, ensure the logic is robust and covers all possible branches. Crucially, always guarantee the function returns a value; otherwise, it can interrupt the content output flow, leading to difficult-to-diagnose display issues.

Post a Comment

Your email will not be published. Required fields are marked with *.