X

Eliminar código innecesario de wp_head

WordPress incluye un montón de cosas a través del hook wp_head() incluido en la mayoría de los temas. La mayoría de estas cosas yo las consideraría innecesarias. Unas pocas líneas de código extra en tu cabecera probablemente no ralentizarán mucho tu sitio, pero me gusta mantener las cosas tan limpias y eficientes como sea posible.

En este post de consejos rápidos, voy a repasar cómo eliminar lo siguiente de la salida a través del gancho wp_head.

  • Enlace a Really Simple Discovery (RSD)
  • Enlace a Windows Live Writer
  • Aviso del generador de WordPress
  • Enlaces relacionales

Siga leyendo para ver la descripción de cada uno de ellos y saber si los necesita o no, y cómo eliminarlos.

Descubrimiento realmente sencillo

Este es el código que muestra el siguiente código en su cabecera:

<link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://example.com/xmlrpc.php?rsd" />

Este es el mecanismo de descubrimiento utilizado por los clientes XML-RPC.  Si no tienes ni idea de lo que esto significa y/o no integras servicios

como Flickr con tu sitio WordPress, probablemente sea seguro eliminarlo con el siguiente código en el archivo de funciones de tu tema.

remove_action('wp_head', 'rsd_link');

Windows Live Writer

Esta es la razón por la que ves el siguiente código en tu cabecera.

<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://example.com/wp-includes/wlwmanifest.xml" />

Si no utiliza Windows Live Writer, entonces este código es completamente inútil para usted y debe ser eliminado.

remove_action('wp_head', 'wlwmanifest_link');

Generador de WordPress

Esto es lo que muestra tu número de versión de WordPress en tu cabecera.

<meta name="generator" content="WordPress 2.8.4" />

Nadie realmente necesita saber la versión exacta de WordPress que está utilizando, por lo que es seguro eliminar esta línea de código.

remove_action('wp_head', 'wp_generator');

Enlaces Relacionales

Los enlaces postrelacionales son la razón por la que este material se muestra en varias páginas.

<link rel='index' title='Página principal' href='http://www.themelab.com' />
<link rel='inicio' title='Artículo en el pasado lejano' href='http://www.themelab.com/hello-world/' />
<link rel='prev' title='El artículo anterior a éste' href='http://www.themelab.com/post-before/' />
<link rel='next' title='El artículo después de éste' href='http://www.themelab.com/post-after/' />

Todavía tengo que encontrar una razón real para mantener estos alrededor.  Algunos navegadores pueden usar este código para navegar por tu sitio, aunque probablemente puedas conseguir el mismo efecto con un tema bien diseñado.  Necesitarás tres líneas para eliminarlas todas.

remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link');

Plantilla Functions.php

Para su comodidad, aquí están todos ellos combinados para facilitar copiar y pegar en el archivo functions. php de su propio tema.

<?php
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link');
?>

De hecho, este es todo el archivo

functions. php que estoy usando en mi nuevo tema de archivo de tweets. Si echas un vistazo al código, la etiqueta <head> sólo contiene tres líneas: la declaración meta charset, la etiqueta title y el enlace stylesheet.

Nota sobre los temas publicados

Cuando desarrolle temas para su publicación, tenga cuidado al eliminar algunos de estos elementos, especialmente los dos primeros: XML-RPC y la compatibilidad con Windows Live Writer.

La razón debería ser bastante obvia, porque algunos de tus usuarios probablemente usarán algo como Windows Live Writer, y volverán a pedirte soporte cuando no puedan entender por qué no funciona con tu tema.

Los otros elementos, el aviso del generador de WordPress y los enlaces de relación de entradas, probablemente pueden ser eliminados con seguridad en casi cualquier situación.

Conclusión

Como dije en la introducción, no es un gran problema si no quita estos elementos y yo no diría que esto es “obligatorio” en cada nuevo sitio WordPress que desarrolle. Si eres como yo y no te gustan las líneas de código inútiles, probablemente querrás hacerlo de todos modos sólo para mantener las cosas funcionando lo más limpio posible.

¿Se te ocurre alguna otra función que utilices para eliminar líneas de código innecesarias de WordPress? Házmelo saber en los comentarios.

Comentarios   Deja una respuesta

  1. Hello, I need help on WordPress that after making the page in WP I saw in the code (source code) that with every class name page builder has added his name which is confusing for me, for example, am using ELEMENTOR and making a page I saw in source code class name “.elementor-column-wrap”… now the problem is I want to remove the elementor words before the class name. I want to keep the class name as simple as that. no page builder name should be there… please let me know.

    1. You can’t remove it or you will break the Elementor

  2. Hello,

    Please tell me where to put this code in functions.php?
    Some blogs told that it should be put at the end, other blogs that it can be put in the beginning?

    Thanks in advance

    1. The position doesn’t matter at all. You can add it at the beginning or bottom.

  3. How can i remove from wp_head()

  4. Hello,
    Thanks for this post but please also add code to remove emoji script.
    Regards

      1. Thank you very much for help. Just want to tell you that my site got speed of 99 on mobile and 98 on desktop in google page speed test because of code mentioned above in post and emoji removal code.

        1. I am glad it helped!

  5. I don’t know why do theme developers put these in their themes as default in the first place.

    I used a very basic theme and modified it to suit my website but all these junk was still in my header (among with some other junk WordPress automatically loads).

    Thanks for this post, I found it very useful.

  6. Just found this post based on the adjacent_posts_rel_link_wp_head – This may work for you and your audience so I think it’s relevant… not trying to spam but…
    I threw a handful of functions and cleanup type of stuff that I hope works for everybody’s installs to help clean it up and get rid of some of the crap like the wp_head stuff you’ve posted here.

    the plugin, for lack of a better name, is Selfish Fresh Start… selfish because it’s the stuff I feel should be removed from every install lol.

    http://wordpress.org/extend/plugins/selfish-fresh-start/

  7. Yes, it used wp_head. Is that something I need to worry about?

  8. I don’t have any of these in my header except for the WordPress generator – in my theme this is in a comment with “leave this for stats please”

    What’s that about?

    1. Does your theme use the wp_head hook? It sounds like that “leave this for stats” bit is hardcoded into your theme’s header.php file.

  9. Great stuff, although I should add that there’s been a little change in WP 3.0 with adjacent_posts_rel_link. It is now adjacent_posts_rel_link_wp_head (not sure why it changed).

    I figured that out by going to /wp-includes/default-filters.php and reversing what was listed in the add_action section.

    Any idea why that would have changed?

    1. We changed its name because we modified (improved) how it works in a backwards incompatible way. Fine for core, as it is an enhancement, but if a plugin was using the original plugin the way core does, we don’t want to alter that functionality.

      The new function actually just calls the old function — http://core.trac.wordpress.org/ticket/10867

  10. Hi. Do you know how I can remove jquery being called automatically? Obviously it needs to be called in the admin site, but client side, I use mootools, so don’t want two js libraries being called.

    Thanks
    Tom

  11. Excellent post Leland! The relational links always bothered me a bit but I never looked into how to remove them.

    I think it’s also worth mention that a lot of the code added by plugins can also be removed: http://wptheming.com/2009/12/optimize-plug-in-script-wordpress/

    1. Hey Devin, thanks for the comment. That’s a good point about plugin code. Especially when plugins like Contact Form 7 automatically load up CSS and JS on every page, when you usually only need it on one (or any page you actually have a contact form).

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!