Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: How to add Attribute to body

I want to add Scrollspy support to the nav-menu, for that I have to add extra attributes data-spy="scroll" data-target=".navbar" to the body tag.

Can I do that pragmatically without touching theme files?

like image 753
Sevi Avatar asked Sep 01 '17 15:09

Sevi


People also ask

Where is the body tag in WordPress?

Click the "header. php" file in the list of files at the right to open it in the Editor. The header. php file contains the body tag.


1 Answers

One way would be to:- Edit header.php And add those attributes to the body.

Alternative (without editing theme files) way would be to create a plugin which adds a js that adds those attributes to body. Something like this:-

$("body").attr( { data-spy:"scroll", data-target:".navbar" } );

EDIT After viewing Sevi's answers. The most suitable way is

function wp_body_classes( $classes )
{
    $classes[] = '" spy="scroll" data-target=".navbar';

    return $classes;
}
add_filter( 'body_class','wp_body_classes', 999 );
like image 162
tousif Avatar answered Oct 05 '22 06:10

tousif