如何在<body>元素后直接添加自定义头部?WordPress插件适配
Hey there, let's sort out this duplicate content issue and get your custom header in the right spot!
The problem with using wp_head is that this hook can sometimes be triggered multiple times—either from a theme accidentally calling wp_head() twice, or plugins hooking into it in a way that causes repeats. To fix this and get your content to load right after the <body> tag on every page, we'll use a more appropriate WordPress hook: wp_body_open.
Here's your updated code:
// First, remove the old hook if it's already active remove_action('wp_head', 'add_custom_header'); // Hook our function to wp_body_open instead add_action('wp_body_open', 'add_custom_header'); function add_custom_header() { // Replace this with your actual custom header content echo '<div class="your-custom-header-class">Your custom header content goes here!</div>'; }
Quick note for older themes:
If your theme is a bit outdated, it might not include the wp_body_open() call in its header.php file. To fix this, open your theme's header.php, find the <body> tag, and add <?php wp_body_open(); ?> immediately after it, like this:
<body <?php body_class(); ?>> <?php wp_body_open(); ?> <!-- Rest of your theme's header content -->
This hook was introduced in WordPress 5.2 specifically for cases like yours—inserting content right after the <body> tag without worrying about duplicate triggers. It's the official, reliable way to handle this now.
内容的提问来源于stack exchange,提问作者Frank

