Wordpress action "wp": Cannot modify header information

862 Views Asked by At

I would want to show some HTML code in my WordPress page. So in my child theme functions.php, I have written an action like this one:

add_action('wp', function() {
    if(is_admin()) {
        return;
    }
    
    $html = '<div class="home_immodvisor">';    

    echo $html; 
});

However, a warning is displayed when I go to the back-office (admin) login page:

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/themes/hello-elementor-child/functions.php:88) in /var/www/html/wp-includes/pluggable.php on line 1296

Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/wp-content/themes/hello-elementor-child/functions.php:88) in /var/www/html/wp-includes/pluggable.php on line 1299

My question is: is it the good action to hook? Or should I use another one than wp?

3

There are 3 best solutions below

4
On

From my understanding wordpress sends headers after wp so this is the wrong place, since you cannot echo before.

0
On

Warning: Cannot modify header information - headers already sent by

To solve this add the below code in theme function.php file

ob_start();

It will remove your error.

0
On

There is no standardized hook/action for inserting a html in a theme. Every theme could handle this differently, some might not even have a hook.

But if you must the wp_head hook will work, but it will not be valid HTML.

The better thing todo is check the documentation of your thema. Or make a child-theme and adjust the tempaltes) you need