WordPress how to modify tag of a page by adding extra html attributes

In wordpress is there a way to set the body tag attribute on a Page like this :

<body onBlur="window.focus()">

WP Block editor does not allow editing the page html, because it is visual editor of course.

I would use this code so I can make a popup window stay always on top.

BTW I solved the problem how to popup the window, just dont know how to make it stay on top

how to create Popup window

If there is other way let me know.


thanks @ruvee

Wrote step by step instruction here: update body tag

Answer

There is a hook you could use called wp_footer. You could add extra attributes to your body tag using pure/vanilla javascript like this:

add_action("wp_footer", "your_theme_adding_extra_attributes");

function your_theme_adding_extra_attributes(){
    ?>
    <script>
        let body = document.getElementsByTagName("body");
        body[0].setAttribute("onBlur", "window.focus()"); 
    </script>
<?php }

Code goes into the functions.php file of your active theme.

This answer has been tested on wordpress 5.8 and works.

enter image description here


Running it on a specific page:

Depending on which page you would need to run it on, you could use different conditional statements. For example:

  • Only on archive pages:
    • is_archive() would be a proper conditional check
  • Only on the index of your blog:
    • is_home() would be a conditional check.
  • Only on front page that may or may not be your blog index:
    • is_front_page() would be a conditional check
  • etc…

UPDATE (related to the second request that was not part of the first question)

If you have a page with a slug of blah and you want to modify its body tag, you could use the following snippet:

# The following code would only get executed on yourwebsite.com/blah

add_action("wp_footer", "your_theme_adding_extra_attributes");

function your_theme_adding_extra_attributes(){
    if(is_page("blah")){ ?>
    <script>
        let body = document.getElementsByTagName("body");
        body[0].setAttribute("onBlur", "window.focus()"); 
    </script>
<?php }
}

is_pageDocs


For people who would need to add an extra class NOT an extra attributes, there is a hook called body_class and there are too many answers already on Stackoverflow, such as: