X

Añadir clase de cuerpo personalizada para páginas específicas

Snippets by IsItWP

¿Está buscando una manera de añadir una clase de cuerpo personalizado para páginas específicas? Si bien es probable que haya un plugin para esto, hemos creado un fragmento de código rápido que puede utilizar para agregar la clase de cuerpo personalizado para páginas específicas en WordPress.

Instrucciones:

Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:

add_filter( 'body_class', 'my_neat_body_class');
function my_neat_body_class( $classes ) {
     if ( is_page(7) || is_category(5) || is_tag('neat') )
          $classes[] = 'neat-stuff';

     return $classes; 
}

Añade este fragmento de código al archivo header.php de tu tema de WordPress para sustituir la etiqueta HTML body predeterminada.

<body <?php body_class(); ?>>

Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo añadir correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.

Si te ha gustado este fragmento de código, por favor, considere revisar nuestros otros artículos en el sitio como: 27 mejores temas de negocios de WordPress y 7 mejores plugins GDPR de WordPress.

Comentarios   Deja una respuesta

  1. Is something similar possible but for a #id? I don’t want class .id

    1. You could still use the .page-id class: https://developer.wordpress.org/reference/functions/body_class/

      That said, for actually ids, you could add an id to the template file itself and use conditionals to control when it displays.

  2. great! really helped me out.

  3. Freelance Web Designer junio 3, 2014 en 3:30 pm

    where can i add class once above steps are done?

    1. change the class in the code ‘neat-stuff’ to whatever you would like. You could even add
      multiple classes if need be.

      1. Freelance Web Designer junio 3, 2014 en 3:39 pm

        i want different id / class for each page… how do i assign it to specific page?

        1. This snippet is not what you need, it will only add a single class to

          “is_page(7) || is_category(5) || is_tag(‘neat’)”

          A page with the ID of 7 or the category of 5 or a page that has the tag neat. I think what would better fit your needs is the following.

          http://wpsnipp.com/index.php/functions-php/add-parent-page-slug-to-body_class/

          This will add the page slug as the class for the page with a prefix of parent-{page_slug}. Other than adding this snippet to the functions.php nothing more needs to be done. Also take a look at this search result for more snippets related to the body_class http://wpsnipp.com/?s=body_class

          I’m sure you can find a few that are useful.

          1. Freelance Web Designer junio 3, 2014 en 4:24 pm

            thanks!

  4. Works flawlessly for me, nice job!

  5. Thanks a lot for this, really appreciated!

  6. Thanks for this, I wanted a shorter body class name for a custom page template, using is_page_template (‘template-name.php’) and this worked perfect.

  7. you this be combined with the other body class snippet so if the pages are not specified they default to have their own page as the class?

    1. Should be able to just do

           if ( is_page(7) || is_category(5) || is_tag(‘neat’) ){
                $classes[] = ‘neat-stuff’;          }else{
                $classes[] = ‘other-class’;

                }

  8. Is there anything you need to do after you add the class? I’m not seeing any way to add a custom class for a page…

    1. Hi Trevor,
      Yes you will need to add the body_class(); function within the body tag I updated the snippet to avoid confusion.

  9. Very handy. Can something simular be done using page parent?

    1. Sure you could do something like this, however if your pages only have a single parent the body_class will already add “page-parent” class to the body. This is only a problem if you have many child pages as each sub page may also be a parent page. What is it that you are trying to do?

  10. Elliott the web design guy mayo 18, 2011 en 10:43 pm

    Now that’s a very neat snippet for custom page layouts – awesome!

    1. Cool glad you like it!

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!