I made an ajax function to make a Single Page Application on my wordpress website and i want to add a class on my body
using that find the
slug
of my pages.
There is my function.php:
function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ){
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );
and there is my ajax.js and my index.php :
$(function() {
/* --- history --- */
$(window).bind('popstate', function() {
var url = window.location;
var hash = url.href.substring(url.href.lastIndexOf('/') + 1);
$('#contenu').fadeOut(500, function() {
$('#contenu').load(url + ' #contenu', function() {
$('#contenu').fadeIn(500, function() {});
});
});
$('#menu li').removeClass('active');
if (hash.length == 0) {
$('#menu li').first().addClass('active');
} else {
$('#menu li.' + hash + '').addClass('active');
}
});
$('.menu-item a').click(function(e) {
e.preventDefault();
$('#menu li').removeClass('active');
$(this).parent().addClass('active');
var lien = $(this).attr('href');
$('#contenu').fadeOut(500, function() {
$('#contenu').load(lien + ' #contenu', function() {
$('#contenu').fadeIn(500, function() {
history.pushState(null, null, lien);
});
});
});
});
});
<div id="contenu" class="vs-section">
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</div>
So it’s working well on refresh but when i load my pages with my ajax function
clicking on #menu li
the slug doesn’t change and so my body class doesn’t change too, how can i fix it?
Read more here: WordPress: Body class of page’s slug in ajax