Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Cómo dar estilo a la estructura / disposición / diseño / plantilla de los comentarios de WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

Recientemente te mostramos cómo dar estilo al formulario de comentarios de WordPress, y pensamos que estaría incompleto si no escribiéramos acerca de cómo dar estilo a la disposición/ diseño / plantilla de comentarios de WordPress. En el pasado, hemos discutido que hay clases CSS generadas por defecto por WordPress e IDs para ayudar a que sea más fácil para los diseñadores de temas dar estilo a sus plantillas. En este artículo, usaremos esas clases por defecto para mostrarte cómo dar estilo a la disposición de comentarios de WordPress y algunas de las cosas interesantes que puedes hacer con ella.

Por el bien de este ejemplo, vamos a modificar el tema por defecto Twenty Twelve WordPress en este artículo. Nota: Este artículo es para diseñadores de temas principiantes y usuarios DIY que tengan un buen conocimiento de HTML y CSS.

Clases de comentarios por defecto de WordPress

Por defecto WordPress genera estas clases para los elementos de la plantilla de comentarios:

/*Comment Output*/

.commentlist .reply {}
.commentlist .reply a {}

.commentlist .alt {}
.commentlist .odd {}
.commentlist .even {}
.commentlist .thread-alt {}
.commentlist .thread-odd {}
.commentlist .thread-even {}
.commentlist li ul.children .alt {}
.commentlist li ul.children .odd {}
.commentlist li ul.children .even {}

.commentlist .vcard {}
.commentlist .vcard cite.fn {}
.commentlist .vcard span.says {}
.commentlist .vcard img.photo {}
.commentlist .vcard img.avatar {}
.commentlist .vcard cite.fn a.url {}

.commentlist .comment-meta {} 
.commentlist .comment-meta a {}
.commentlist .commentmetadata {}
.commentlist .commentmetadata a {}

.commentlist .parent {}
.commentlist .comment {}
.commentlist .children {}
.commentlist .pingback {}
.commentlist .bypostauthor {}
.commentlist .comment-author {}
.commentlist .comment-author-admin {}

.commentlist {}
.commentlist li {}
.commentlist li p {}
.commentlist li ul {}
.commentlist li ul.children li {}
.commentlist li ul.children li.alt {}
.commentlist li ul.children li.byuser {}
.commentlist li ul.children li.comment {}
.commentlist li ul.children li.depth-{id} {}
.commentlist li ul.children li.bypostauthor {}
.commentlist li ul.children li.comment-author-admin {}

#cancel-comment-reply {}
#cancel-comment-reply a {}

Cómo encontrar las clases CSS que necesitas editar

Antes de pasar a estilizar la estructura / disposición / diseño / plantilla de comentarios de WordPress, un pequeño consejo para nuestros nuevos usuarios. Los navegadores Google Chrome y Mozilla Firefox vienen con una útil herramienta que puedes usar para mejorar tus habilidades en el desarrollo de temas para WordPress. La herramienta se llama Inspeccionar elemento. Simplemente lleve el ratón a un elemento de una página web, haga clic con el botón derecho y elija inspeccionar elemento. La ventana de tu navegador se dividirá en dos filas y en la ventana inferior verás el código fuente de ese elemento. También en la ventana inferior podrás ver los elementos CSS y su estilo. Incluso puedes editar el CSS para hacer pruebas. Es importante recordar, que cualquier cosa que cambies usando el Elemento de Inspección es solo visible para ti. En el momento en que actualices la página, esos cambios desaparecerán. Para hacer los cambios permanentes, tienes que usar tu archivo style.css u otros archivos apropiados en tus temas.

Inspect element in Google Chrome to look at source code and quickly find matching CSS rules

Añadir colores de fondo pares e impares para los comentarios

Tener un color de fondo diferente para los comentarios pares e impares es una tendencia de diseño que existe desde hace algunos años. Ayuda a la legibilidad, especialmente si tienes muchos comentarios. También se ve muy bien con ciertos colores de tema que es la razón por la que muchos diseñadores quieren utilizar esta funcionalidad. Para ayudar a los diseñadores a lograr este objetivo, WordPress añade una clase par e impar a cada comentario respectivamente.

Puedes añadir fácilmente el estilo par/impar para los comentarios en el style.css de tu tema pegando el siguiente código.

.commentlist .even .comment { 
background-color:#ccddf2; 
} 
.commentlist .odd .comment {
background-color:#CCCCCC;
}

El resultado sería algo parecido a esto:

Using CSS to add alternate colors for even and odd comments in WordPress

Estilización del autor del comentario y la metainformación

WordPress también añade clases a los elementos mostrados en la cabecera de cada comentario. Esto permite a los diseñadores de temas personalizar la visualización de la información del autor y otros meta comentarios como la fecha y hora del comentario. Aquí hay un ejemplo de código para pegar en el archivo style.css de su tema para dar un estilo diferente a estos elementos. En este ejemplo hemos añadido color de fondo a la meta comentario junto con un poco de espaciado.

.comments-area article header {
	margin: 0 0 48px;
	overflow: hidden;
	position: relative;
	background-color:#55737D;
	color:#FFFFFF;
	padding: 10px;
}

Así es como debería verse:

Styling comment meta and author information in WordPress comments

Diferentes estilos para los comentarios del autor de la entrada

A menudo puede ver que los comentarios del autor de la entrada se resaltan con un color de fondo diferente o con alguna acreditación / insignia / distinción adicional. WordPress añade una clase por defecto bypostauthor a todos los comentarios hechos por el autor de la entrada. Los diseñadores de temas de WordPress pueden utilizar esta clase para dar un estilo diferente a los comentarios del autor de la entrada.

Algunos temas, utilizan su propia función callback para mostrar los comentarios. Usando la función callback, estos temas pueden añadir información adicional a un comentario por autor de entrada. Por ejemplo, Twenty Twelve utiliza la siguiente línea en la función callback del comentario twentytwelve_comment() (ubicada en el archivo functions.php del tema).

// If current post author is also comment author, make it known visually.

( $comment->user_id === $post->post_author ) ? '<span> ' . __( 'Post author', 'twentytwelve' ) . '</span>' : '' );

Este código añade <span>Autor de la entrada</span> a la meta información del comentario. Dependiendo de cómo tu tema de WordPress maneje los comentarios del autor de la entrada, puedes modificarlo a lo que quieras.

Si estás usando un tema diferente a Twenty Twelve, entonces necesitas averiguar cómo tu tema maneja los comentarios. Simplemente abre el archivo comments.php de tu tema. Si tu tema utiliza su propia función de devolución de llamada, la verás dentro de la función wp_list_comments, así:

<?php wp_list_comments( array( 'callback' => 'twentytwelve_comment', 'style' => 'ol' ) ); ?>

En el ejemplo anterior, se puede ver que el tema está utilizando twentytwelve_comment como la función de devolución de llamada. Si se especifica una función de devolución de llamada, entonces la ubicación más probable para encontrar esta función es en el archivo functions.php de su tema.

En este ejemplo estamos cambiando esta función para mostrar Editor en lugar de Autor de la entrada. Para ello hemos modificado la función callback del comentario de la siguiente manera:

// If current post author is also comment author, make it known visually.

( $comment->user_id === $post->post_author ) ? '<span> ' . __( 'Editor', 'twentytwelve' ) . '</span>' : '');

También vamos a modificar la forma en que se ve añadiendo lo siguiente en el archivo style.css de nuestro tema así:

li.bypostauthor cite span {
	color: #21759b;
	background-color: #f8f0cb;
	background-image: none;
	border: 1px solid #f8f0cb;
	border-radius: 3px;
	box-shadow: none;
	padding: 3px;
	font-weight:bold;
}

Así es como quedaría:

Styling aurhor comments differently in WordPress comments

Estilizar el enlace de respuesta al comentario en los comentarios de WordPress

La mayoría de los temas de WordPress tienen un enlace de respuesta debajo de cada comentario. Esta funcionalidad solo se muestra si tienes activados los comentarios enlazados. Para activar los comentarios enlazados, vaya a su administrador de WordPress(Ajustes ” Discusión). Busque en la sección donde dice otros ajustes de comentarios, y marque la casilla para activar los comentarios enlazados (anidados).

Las clases CSS generadas por defecto por WordPress para enlazar la respuesta son reply y comment-reply-link. Usaremos esas clases para modificar el enlace de respuesta y convertirlo en un botón CSS.

.reply { 
	float:right;
	margin:0 10px 10px 0;
	text-align:center;
	background-color: #55737D;
	border:1px solid #55737D;
	border-radius:3px;
	padding:3px;
	width:50px;
	box-shadow: 1px 1px 2px 2px #4f4f4f;
}

.comment article {
	padding-bottom:2.79rem;
}

a.comment-reply-link,
a.comment-edit-link {
	color: #FFFFFF;
	font-size: 13px;
	font-size: 0.928571429rem;
	line-height: 1.846153846;
	text-decoration:none;
}

a.comment-reply-link:hover,
a.comment-edit-link:hover {
	color: #f6e7d7;
}

Así es como quedaría:

Styling the comment reply button in WordPress comments using CSS

Botón de edición de comentarios

En la mayoría de los temas de WordPress, los usuarios conectados con capacidad para editar comentarios pueden ver un enlace de edición de comentario debajo de cada comentario. Aquí hay un poco de CSS que utiliza la clase por defecto comment-edit-link para modificar la apariencia del enlace.

a.comment-edit-link {
	float:left;
	margin:0 0 10px 10px;
	text-align:center;
	background-color: #55737D;
	border:1px solid #55737D;
	border-radius:3px;
	padding:3px;
	width:50px;
	box-shadow: 1px 1px 2px 2px #4f4f4f;
}

Así es como se vería:

Using CSS to style comment edit link in WordPress Comments

Estilo Cancelar comentario Enlazar respuesta

En la mayoría de los buenos temas de WordPress, al hacer clic en el enlace Responder se abre el formulario de comentarios justo debajo del comentario al que estás respondiendo con un enlace para cancelar la respuesta al comentario. Vamos a modificar este enlace para cancelar la respuesta al comentario utilizando el ID CSS por defecto cancel-comment-reply.

#cancel-comment-reply-link  { 
	text-align:center;
	background-color: #55737D;
	border:1px solid #55737D;
	border-radius:3px;
	padding:3px;
	width:50px;
	color:#FFFFFF;
	box-shadow: 1px 1px 2px 2px #4f4f4f;
	text-decoration:none;
}

Así es como quedaría:

Styling the cancel comment reply link in WordPress comment reply form

Estilo del formulario de comentarios de WordPress

Los formularios de comentarios usables, estéticamente agradables y con estilo animan a los usuarios a dejar un comentario en tu blog. Anteriormente hemos escrito un artículo detallado acerca de cómo dar estilo al formulario de comentarios de WordPress. Te recomendamos que lo compruebes para ver cómo puedes llevar tu formulario de comentarios de WordPress al siguiente nivel.

Esperamos que este artículo le ayude a dar estilo a su disposición / diseño / plantilla de comentarios de WordPress. Si tienes alguna pregunta o sugerencia, por favor no dudes en dejarnos un comentario abajo.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

41 comentariosDeja una respuesta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

    • WPBeginner Support says

      The code in this article is CSS code, you would want to add it under Appearance>Customize>Additional CSS for the code to affect your site.

      Administrador

  2. Prashant says

    I have my site where i have the replies to comments appear right below in straight line below the actual comment.. how can we put a small offset like you have done here for the replies to comments?

  3. Will says

    It’s 2018!

    Is this still the easiest method to style a WordPress comment?

    This article was written 5 years ago. A search around Google. It seems like the WordPress comment system is NOT beginner-friendly to customize, and hasn’t evolved much at all. Disappointing!

  4. Henry says

    Great Tutorial!
    But how do I get the comments to show up side by side (Like a “for” and “against”) kind of debate to a single post. Also will I need to have two different comment forms underneath them?

  5. Mike says

    Hi,

    How can I style the hyperlinks in the comments area? I want to change the hyperlink color in the comments box.

    Thank-you.

    Mike

  6. Aaron says

    Hey WPBeginner,

    Awesome post! I read through it and am still having trouble figuring out what I need to do to display the “Reply” button and Gravatars.

    I’m not sure if the theme displays this information, but I do have Avatars enabled in the Reading section of the admin panel.

    I thought maybe I could place a bit of code somewhere in the comments.php file, but I don’t see where I could add these changes manually. The part of the code that brings comments in looks something like this:

    ~~~~

    Recent Comments

    ‘comment’, ‘callback’ => ‘crawford_comment’)); ?>

    ~~~~

    Am I looking in the wrong place? Answer is probably yes, but I’m not sure where to check.

    Here’s a page with comments, for reference:
    Any advice appreciated!

    • WPBeginner Support says

      The comments.php template is pointing to you to look for the callback function. This callback is defined in your theme’s functions.php file. This is where you will edit your comment layout.

      Administrador

  7. Imad Daou says

    Would you please show the same steps but for Gensis 2.0? I followed the above steps, but I still couldn’t figure out how to change the comment layout background color. I use Genesis Sample theme.

    My website under development and I can’t have it live yet, but the dropbox links below will show you how the comments boxes are white and I couldn’t find out using all the tricks you mentioned above how to change the color background color.

    I wanted to use #333333 as background instead of white.

    Thank you so much for all your hard work.

  8. Wakhid says

    Hi WPbeginner, im trying to create a custom form comments but i really don’t know how to create it,

    sorry my english is bad

  9. Derek says

    I followed this tutorial and have only one question:

    How can you get the reply box to appear nested under the post you are replying to?

    • Arauz says

      Im add in this question too. I have a template but i cant show the nested comments from the admin of the site.

      Help us please.

  10. Charlene says

    Wow all of these tips have been so helpful! Thanks for a great post!

    I’m now wondering how can I add text beside all Admin names in the comments, even if they’re not the post author?

    I’m assuming it would be here but not sure what needs to be changed:
    ‘( $comment->user_id === $post->post_author )’

    Thanks!!

  11. Geoffrey says

    Careful on line 44 of default WordPress comments classes,


    .commentlist li ul.children li.depth-{id} {}

    is not a valid CSS selector. {id} must be replaced with the appropriate ID (an integer).

  12. hellobass says

    .commentlist .reply {}
    .commentlist .reply a {}

    Where are the “-” in your exemple (‘Default WordPress Comments Classes’)?

    because its : .comment-list

    • WPBeginner Support says

      hellobass, actually .commentlist or .comment-list is not generated by WordPress and themes usually choose them on their own. For example, Twenty Twelve uses .commentlist and Twenty Thirteen uses .comment-list you can find out which class your theme is using by look at comments.php or in Chrome developer tools (Inspect Element).

      Administrador

  13. Avner says

    Thank you! that was very helpful!

    How can I apply the odd and even styling to apply only inside a thread (in order to distinguish between child comments)? I would like the readers to be able to distinguish easily between comments in the same thread and allow them to follow it easily.

    Thanks!

  14. Audee says

    Is there any tips to style very deep levels of nested comments in WordPress?
    :D I must have been crazy for styling 5 deep levels nested comment.
    It will be nice and save up much time to have a set of CSS code which is reusable for different project. But often happened that different layout width might made this reusable styling took longer to configure.

    Thank you for sharing this article, bookmarked for further study ;)

  15. Adam says

    This is so annoying i can not get half of this to work
    the odd and even colours only apply to the nested comments
    It will not let me style the Comment Author and Meta Information at all
    Please help me Fix this

  16. rolanstein says

    Excellent post! Thank you.

    May I ask how you add the ‘Notify me of followup comments via e-mail’ and ‘Subscribe to…’ boxes below your comment form?

    Cheers
    rolanstein

  17. Jannik says

    Awesome Tutorial!
    How did you get rid of the – ordered list? It always has numbers infront of my comments and I really don’t like it.

    Thanks!

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.