Remove Wordpress Body Classes

10,718

This is how you find something like this out:

  1. Find the relevant function by looking in a theme file, in this case header.php

  2. Look this function up in the Wordpress Codex (http://codex.wordpress.org/Function_Reference/body_class)

  3. Is there any examples that look similar to what I want to do? Yes:

    // Add specific CSS class by filter add_filter('body_class','my_class_names'); function my_class_names($classes) { // add 'class-name' to the $classes array $classes[] = 'class-name'; // return the $classes array return $classes; }

So basically, to remove all classes, just add this to functions.php:

add_filter('body_class','my_class_names');
function my_class_names($classes) {
    return array();
}

t 4. But I want to keep page id and post id - how can I do that? Because you don't know on what index in the array that you can find this information on, and searching through the array is lame, you need to first empty the array like we did above, and then add the stuff you really want. How do you get the right information, that is, page id and post id? This is step five.

(5) At the bottom of the codex page you will find a link to the source code. This is the link you'll find: http://core.trac.wordpress.org/browser/tags/3.2.1/wp-includes/post-template.php If you look at the function, you'll see it uses a function which simply populates the same array that we can manipulate with aforementioned filter. By looking how they do it, you can do it too.

add_filter('body_class','my_class_names');
function my_class_names($classes) {
    global $wp_query;

    $arr = array();

    if(is_page()) {
    $page_id = $wp_query->get_queried_object_id();
    $arr[] = 'page-id-' . $page_id;
    }

    if(is_single()) {
    $post_id = $wp_query->get_queried_object_id();
    $arr[] = 'postid-' . $post_id;
    }

    return $arr;
}

Hopefully this code works. If it does not, try to figure out what's wrong by following the steps above. I hope I helped at least a little bit :)

Share:
10,718
Chris Burton
Author by

Chris Burton

Pre-Law.

Updated on July 21, 2022

Comments

  • Chris Burton
    Chris Burton almost 2 years

    How could I remove classes from the body element in Wordpress?

    Default: body class="page page-id-7 page-template-default logged-in"


    What I'm looking for: body class="page-id-7"

    On Post's: body class="postid-40"