Published on Jul 27, 2020

How to Add Custom Attributes to the Body Element in Oxygen

David Browne

Custom attributes are the latest feature to be announced in Oxygen 3.5, this provides us with an easy way to add extra data to elements in Oxygen.

Custom attributes are useful for lots of reasons, but one thing we aren’t able to do from inside the Oxygen UI is to add custom attributes to the body element itself.

The reason is that the templates and pages that we create inside Oxygen are already inside the body element, which itself is hardcoded into the main Oxygen template file.

There are times when adding attributes to the body elements may be useful..

  • Adding schema markup to a page (https://schema.org/WebPage)
  • Adding data attributes for a JS library to use (eg scroll spy)
  • You may need to give the body element an ID on a specific page.

Conditionally Adding Attributes

There is a handy action hook provided to us in Oxygen ‘oxygen_vsb_body_attr’ that we can make use of. This will output directly inside the body element so we can add our attributes.

We can use conditional statements to ensure these attributes are only added to the pages we need them across the site.

In a code snippet, or from inside a functionality plugin, here’s how we could use that hook to add some schema microdata to the body element.

// Add custom attributes to the body tag
add_action('oxygen_vsb_body_attr','lit_body_schema_attr');
function lit_body_schema_attr() { 
// Attribute name/value pairs as array
$array = array(
'itemprop'  => 'https://schema.org/WebPage',
'itemscope' =>'',
);
foreach ($array as $key => $value) {
echo $key . '="' . $value . '" ';
}
}

or say we wanted to add some data attributes to the body element only on a specific landing page, for eg for adding scrollspy, we could add a conditional statement to target only that page…

// Add custom attributes to the body tag
add_action('oxygen_vsb_body_attr','lit_scrollspy_attr');
function lit_scrollspy_attr() {
// Abort if not on the page 'landing'
if ( !is_page('landing') )
return;    
// Attribute name/value pairs as array
$array = array(
'data-spy'     => 'scroll',
'data-target'  => '.header-navigation',
'data-offset'  => '80',
);
foreach ($array as $key => $value) {
echo $key . '="' . $value . '" ';
}
}

All done

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right