Cómo cambiar los atributos de los títulos en WordPress

Tener un sitio web o un blog de WordPress sin gestionar los títulos es bastante imposible. Si alguna vez te has olvidado de escribir un título, te habrás dado cuenta rápidamente de que WordPress lo añade por sí mismo. Dado que son importantes para los administradores, otros usuarios, los visitantes e incluso los motores de búsqueda, debes tener especial cuidado al escribir los títulos.

Aunque definitivamente deberías dedicar un minuto extra a cada título que escribas, hay algunas cosas que puedes cambiar en todo el sitio. Así que, quédate con nosotros en esta guía y aprende a modificar los diferentes atributos de los títulos en WordPress.

Índice de Contenido
  1. Cómo limitar la longitud del título de WordPress
  2. How to change the alignment of your post title
  3. Escribe una lista de palabras que no pueden usarse en los títulos de las entradas
    1. Eliminar palabras específicas de los títulos:
  4. A small title separator change can make a big impact on your site
    1. Change title separator:
    2. Change title separator for older versions of WordPress
    3. Create a static title tag for all of your posts:
    4. Change title tags through custom fields:
  5. Controla tus títulos en WordPress

Cómo limitar la longitud del título de WordPress

Cuando quieres que los títulos de tus entradas sean lo más cortos posible y trabajas con varios autores, eso puede convertirse en un problema. Tanto si estás empezando un blog de moda, como un blog de comida o cualquier otro tipo de sitio web, todos tendrían que ocuparse de sus títulos, contar las palabras o las letras y probablemente sería difícil hacerlo cada vez que escribas un nuevo artículo.

Entonces, ¿cómo limitar el título de una entrada en WordPress para que se encargue automáticamente de la longitud del título que se muestra en tu página?

Empecemos con una solución sencilla.

  1. Abre functions.php en tu tema
  2. Pega el siguiente código:
function max_title_length( $title ) {
$max = 20;
if( strlen( $title ) > $max ) {
return substr( $title, 0, $max ). " …";
} else {
return $title;
}
}
  1. Place the next function wherever you want in your theme. For example, if you want to show shortened titles on your homepage, you want to place this code into your Main Index Template (index.php)
add_filter( 'the_title', 'max_title_length');

As you can see in the code, variable $max is used to limit the length of your post title. You are free to change it to any number you want. But be aware that the optimal length of your title is between 55 and 60 characters.

There you go. If you have called the function in your Main Index Template, your titles will be displayed shortened and after, in our case 20 characters, three dots will be revealed to show there is more to display.

By doing the same, you are free to hook the function wherever you want it – be it header, footer, sidebar or anything else.

How to change the alignment of your post title

WordPress Themes which you can use in WordPress are different. You can use a standard one that comes with WordPress, create your own, find a free one among thousands of available themes, or purchase a premium one from the Internet.

Even if you have paid big bucks for your theme, it won’t have everything in reach of your hand and it’s impossible to incorporate everything into a user-friendly interface. So, if you want to change the alignment of your post titles and your theme doesn’t come with an easy-to-change option, you will have to do it yourself.

Prepare your tools and let’s loose some screws so you can get the job done. OK, this sounded like there are hours of work before you – don’t worry, you’ll be done in a minute or so.

It doesn’t matter which theme you’re using, a title for your post will be located in the same file:

  1. Navigate to Appearance->Editor
  2. On the right side, find Single Post file (single.php) and open it or even better, open the file in some external editor
  3. Search file for “<?php the_title(); ?>“
  4. Modify the tag with the desired alignment:

LEFT:

<div align="left"><?php the_title(); ?></div>

CENTER:

<div align="center"><?php the_title(); ?></div>

RIGHT:

<div align="right"><?php the_title(); ?></div>
  1. Guarda los cambios

Eso es todo. Ahora puedes abrir cualquiera de tus entradas y ver los cambios que has hecho. Si has seguido los pasos y has cambiado la alineación, el título de tu entrada debería aparecer a la izquierda, al centro o a la derecha.

Trabajar con WordPress es divertido, ¿verdad? Si quieres aprender más sobre la creación de blogs y la personalización de WordPress, consulta nuestros recursos y sube de nivel tus habilidades de webmaster en poco tiempo.

Escribe una lista de palabras que no pueden usarse en los títulos de las entradas

Aunque puedes limitar con relativa facilidad la longitud de un título en WordPress, a veces tendrás que modificar los títulos aún más. Limitar el número de caracteres de un título de entrada puede ayudarte a mantener un diseño estable y puede ayudar con el SEO, pero tus autores seguirán pudiendo escribir lo que quieran.

Dependiendo de lo que escribas o de tu asociación con alguna otra empresa, puede que tengas algunas palabras o frases que quieras evitar en tus títulos. Pueden ser palabras soeces que quieras evitar o simplemente un nombre de marca o dos que no quieras que se anuncien en tu sitio.

Aunque puedes sentarte a hablar con tus autores sobre ello y pedirles que no mencionen palabras que puedan dañar la reputación de tu sitio, es cuestión de tiempo que uno de los autores se olvide de ello y publique un título que te haga quedar mal o incluso que pierda dinero al incumplir el acuerdo con un socio.

Lista de palabras que no deben utilizarse en los títulos

En lugar de una advertencia verbal, ¿por qué no escribes una función que prohíba a cualquier persona de tu sitio web escribir un título con determinadas palabras? O mejor aún, ¿por qué no copias y pegas la misma función de abajo y simplemente cambias las palabras que quieres bloquear?

Ahora que has decidido eliminar palabras específicas de los títulos de las entradas, vamos a ver cómo puedes hacerlo.

Eliminar palabras específicas de los títulos:

  1. Abrir el archivo functions.php
  2. Copia y pega el código:
function titlerestriction($título){
global $post;
$título = $post->título_de_post;
$palabrasrestringidas = "palabra1;palabra2;palabra3";
$palabrasrestringidas = explode(";", $restrictedWords);
foreach($palabrasrestringidas como $palabrasrestringidas){
if (stristr( $título, $palabra restringida))
wp_die( __('Error: Has utilizado una palabra prohibida
en el título de la entrada') );
}
}
add_action('publish_post', 'titlerestriction');
  1. Change words on the 4th Add as many as you like but don’t forget to separate them with a semicolon
  2. Customize the error message on the 8th line
  3. Save changes

If you open a new post and try to publish it while the title contains one of the words you have specified in the code, WordPress will stop you from publishing the post and warn you with the message.

Although you may have told your authors about forbidden words, it wouldn’t hurt to show those words right below the title and write them as a reminder.

If it’s not top-secret, can you tell us which words have you put on the list and why?

A small title separator change can make a big impact on your site

Title separator is that one simple character that separates your website title from post and page names. Although as not important as finding the right keywords for your articles, this can be seen on top of your browser tab once you open a website, but more importantly, this separator will be used by Google and other search engines when they display your site in search results.

While there is no proof that different separators can have a different impact on your SEO, you might want to change the standard separator just in order to change the way your WordPress website is being displayed on all the other sites in those search results.

Change title separator:

After WordPress 4.4 came to life, there were new filters introduced, and one of them is directly in charge of title separators. In order to change your title separator, follow these few steps:

  1. Open functions.php file
  2. Copy and paste the following code:
function wploop_change_separator()
{
return '|';
}
add_filter('document_title_separator', 
'wploop_change_separator');
  1. Change the separator in between single quotes on the third line
  2. Save changes

Change title separator for older versions of WordPress

Before WordPress 4.4 was introduced, title separator could have been easily changed by using the wp_title function. WordPress developers first removed the function from the list of supported ones and it became deprecated. But since a huge number of themes are still using it, developers decided to bring it back.

The following function can still help you change that separator if you’re using older WordPress version, but we advise that you update your WordPress as soon as possible (for many different reasons) and go with the new method shown above; sooner or later, wp_title function will become deprecated once and for all and you will have to modify functions.php once again.

function change_wp_title_separator( $title, $sep ) {
$sep = '-';
$title = str_replace( '|', $sep, $title );
return $title;
}
add_filter( 'wp_title', 'change_wp_title_separator', 
10, 2 );

While you can change the separator to any character you want, we advise not to do so. For example, there are some special characters that Google simply won’t show and you don’t want your site title to look unprofessional. Some of the most common separators are “|”, “-“ and “>” so don’t exaggerate and choose the one you like the best.

Title tags are important for your website. Not only they will show up to users, but they will take an important role in your SEO. Choosing the right title tag can have a big impact on search engines and you can benefit from changing title tags if done correctly.

For a regular user, it is easy to change title tags simply by navigating to Settings -> General. Similarly, going to Appearance -> Customize will show a place where almost every theme will allow you to change your site’s title and tagline. Usually, websites use their title and post/page name, separated by one character. But you can change that if you want to be so rebellious.

Create a static title tag for all of your posts:

Although not recommended, you might want to change the page title tag and make it the same on all of your WordPress posts and pages. Instead of using a title, separator and post name, for example, you can change that into something static:

  1. Open functions.php file
  2. Copy and paste the following:
function same_title_tag()
{
return 'First Site Guide';
}
add_filter('pre_get_document_title', 
'same_title_tag');
  1. Change the title on the 3rd line
  2. Save changes

This function would change every post and page title into “First Site Guide” (hey, don’t use our name, be creative), but that’s acceptable if you’re about to have one page only. Instead, using default titles is a much better option when it comes to SEO and overall user experience. Even if you had only home and contact page, it’s still a better option to have that “contact” part written in the title tag.

Change title tags through custom fields:

But, let’s build upon this and give your authors the possibility to add custom titles to their posts:

  1. Open functions.php
  2. Copy and paste the code:
function post_meta_title_tag()
{
$customPostTitleMeta = get_post_meta( get_the_ID(),
'custom_post_title', true);
if($customPostTitleMeta)
{
return $customPostTitleMeta;
}
return '';
}
add_filter('pre_get_document_title', 
'post_meta_title_tag');
  1. Guarda los cambios
  2. Abrir una entrada a la que quieras cambiar el título
  3. En el nombre del campo personalizado, escribe "custom_post_title"
  4. En el valor del campo personalizado, escribe cualquier título que quieras utilizar para esa entrada
  5. Guarda los cambios/publica una entrada

Ahora, en lugar de obtener un título por defecto, tu post utilizaría el personalizado que has introducido en el 6el paso. Si dejas fuera el campo personalizado, WordPress cargará la etiqueta de título por defecto y la utilizará para esa entrada.

Controla tus títulos en WordPress

Esperamos que esta guía te haya ayudado a controlar los títulos de tu WordPress más fácilmente. Pero si tienes alguna pregunta, no dudes en dejar un comentario y trataremos de responderla lo antes posible.

Si quieres conocer otros artículos parecidos a Cómo cambiar los atributos de los títulos en WordPress puedes visitar la categoría Tutoriales.

¡Más Contenido!

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Go up