In order to refresh the classes on the <body>element after an AJAX call, I am writing at the top of my AJAX response the following in JSON: $o[ 'classes' ] = get_body_class('project');

I can then see in the JSON response the following:

"classes":["single","single-project" ,"postid-1793","logged-in","project","default"]

What I am trying to do is to put all those classes into the body using jQuery in order to "refresh" them and transfer the informations regarding the classes of the current template loaded in AJAX.

var thecontent_classes = data.classes;

With the previous code, it is unfortunately not working because it is adding the JSON list with all the classes separated by comas if I'm testing the content of the variable with an alert. I tried to replace the comas by spaces using str.replace without success... Maybe there is an easier way, either with the PHP side or with the str replace ??

Thank you for your time and help.

1 Answer 1


get_body_class() is going to return an array of classes, which is then (per code not published in your question) JSON encoded into that comma separated string. While you can manipulate that in JavaScript, the easiest thing to do is implode the string before encoding:

$c = get_body_class('project');
$c = implode($c,' ');

You should have a nice neat space separated string that you don't have to manipulate further.

  • Working great at the top of my few ajax specific templates with $myNewClasses = get_body_class('project'); $myNewClasses = implode($myNewClasses, ' '); $o[ 'classes' ] = $myNewClasses; I didn't know about this implode() function. Thank you for the help and fast answer !
    – JetXS
    Jun 2, 2015 at 14:32
  • 1
    implode() is Core PHP. It is worth browsing the PHP docs once in awhile ;)
    – s_ha_dum
    Jun 2, 2015 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.