[Resolved] Body class

Home Forums Support [Resolved] Body class

Home Forums Support Body class

Viewing 14 posts - 1 through 14 (of 14 total)
  • Author
    Posts
  • #305855
    Chad Biggs

    How is the best way to add a body class for a specific page?

    #305869
    Jamal

    Hi Chad

    Looking at the documentation it looks like we can use the following

    add_filter( 'body_class','my_body_classes' );
    function my_body_classes( $classes ) {
     
        if ( is_shop() ) {
         
            $classes[] = 'class-name';
            $classes[] = 'class-name-two';
             
        }
         
        return $classes;
         
    }

    https://code.tutsplus.com/tutorials/adding-to-the-body-class-in-wordpress–cms-21077

    Hope that works for you.

    #305991
    Tom
    Lead Developer
    Lead Developer

    Yep, that’s perfect πŸ™‚

    For a specific page, you would replace is_shop() with is_page( 'page-slug' )

    #306190
    Chad Biggs

    Thank you Jamal and Tom.

    #306303
    Tom
    Lead Developer
    Lead Developer

    Glad we could help πŸ™‚

    #789177
    Jonathan

    How would you add the page/post name (title) to the function so that you don’t have to hard code the class?

    i.e If I have an about page I would want the body to include .about as a class

    #789287
    Leo
    Staff
    Customer Support

    Any reason you don’t want to use the unique .page-id-xxx class that comes with each page?

    It should work exactly the same.

    #789766
    Jonathan

    Semantic reasons. The class .page-id-xxx is meaningless while I .about-us is clear.

    #789773
    Jonathan

    I used this piece of code in functions.php of my child theme to make the class:

    add_filter( 'body_class', 'sk_body_class_for_pages' );
    
    function sk_body_class_for_pages( $classes ) {
    
      if ( is_singular( 'page' ) ) {
        global $post;
        $classes[] = 'page-' . $post->post_name;
      }
    
      return $classes;
    
    #790157
    Leo
    Staff
    Customer Support

    Awesome πŸ™‚

    #880099
    Jonathan

    Anyone know how to make a class based on the meta value? So if I create a custom field called ‘my-body-class’ and have a value of ‘whatever is put in here’ what do I need to show the value part?

    #880312
    David
    Staff
    Customer Support

    Hi there,

    try this:

    <?php
    function db_custom_field_body_class($classes) {
    if(get_post_meta(get_the_ID(), 'custom_body_class', true))
        $classes[] = get_post_meta(get_the_ID(), 'custom_body_class', true);
        return $classes;
    }
    
    add_filter('body_class','db_custom_field_body_class');
    ?>

    the custom field name is: custom_body_class or whatever you want to change it to.

    #887759
    Jonathan

    Thanks. That worked well.

    #887775
    David
    Staff
    Customer Support

    You’re welcome

Viewing 14 posts - 1 through 14 (of 14 total)
  • You must be logged in to reply to this topic.