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

Need help implementing a tutorial in your site or want to hire me for custom work?

HIRE ME

Find the article helpful and wish to donate?

DONATE

Comments

You need to be logged in to view and post comments.
Not a member yet? Join here.
magnifiercross
>
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
%d bloggers like this: