programing

Remove Wordpress Body Classes

yellowcard 2023. 11. 6. 21:44
반응형

Remove Wordpress Body Classes

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"

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 :)

currently working code to remove and add a class

//remove body class

add_filter('body_class', function (array $classes) {
    if (in_array('class_name', $classes)) {
      unset( $classes[array_search('class_name', $classes)] );
    }
  return $classes;
});

// Add specific CSS class by body.
 add_filter( 'body_class', function( $classes ) {
    return array_merge( $classes, array( 'class-name' ) );
} );

ReferenceURL : https://stackoverflow.com/questions/7799089/remove-wordpress-body-classes

반응형