Grow your CSS skills. Land your dream job.

Add Same Custom Body Class to Multiple WordPress Pages

  • # June 21, 2014 at 4:16 pm

    Currently, I’m running this bit of code in my functions.php to generate a manageable class based off of the page slug:

    // Add page slug to the body as a class
    
    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' );
    

    But I need something more. A bit of code to generate the same class on multiple pages of my choosing. Basically, on this site here, I’m going to have a lot of galleries. Like a hell of a bunch. And in my CSS, I’d like to be able to target all of my galleries in one swoop with a single class. Is this even possible? I need to be able to add a single class, like gallery, to the pages I specify within WordPress. Any and all help will be muchly appreciated.

    # June 25, 2014 at 3:38 pm

    No takers? There’s got to be a way to do this. Please help me. Thank you muchly!

    # June 25, 2014 at 4:28 pm

    Wouldn’t it be a lot simpler just to create a child template called gallery and add the class to that?

    Otherwise you will have to find something unique that is only found in the gallery pages.

    # June 26, 2014 at 1:31 pm

    When I look up how to create a child template in Google, all that comes up are “child theme” tutorials. So, currently I’m using theDefault Template within my theme on my gallery pages, so I figured if I copied the index.php and added…

    <?php
        /* Template Name: Gallery */
    ?>
    

    …to the top and changed the template to Gallery within the page settings it would work, but it’s not. The page loads just fine, but it looks nothing like it did when I had Default Template selected.

    Can you help me with this or should I contact the theme creators?

    # June 28, 2014 at 3:07 am

    You may want copy the single.php file content and not the index.php depending on what page you are trying to load. Then again if you are using a theme someone created then you will need to see if they are using their own custom template that your page was loading with and copy that.

    # June 28, 2014 at 8:31 am

    Yep, my thoughts exactly, @davidlab.br, so I contacted the theme creators to see what they’re using.

    Edit: Also, this is unrelated, but is anyone else having difficulties starting new topics?

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".