X

Remover código desnecessário do wp_head

O WordPress inclui muitas coisas por meio do gancho wp_head() incluído na maioria dos temas. Eu consideraria a maioria dessas coisas desnecessárias. Algumas linhas de código extra em seu cabeçalho provavelmente não deixarão seu site muito lento, mas gosto de manter as coisas o mais limpas e eficientes possível.

Nesta postagem de dicas rápidas, abordarei como remover o seguinte da saída por meio do gancho wp_head.

  • Link do Really Simple Discovery (RSD)
  • Link do Windows Live Writer
  • Aviso do gerador do WordPress
  • Links relacionais de postagem

Continue lendo para ver a descrição de cada um deles, para saber se você precisa deles ou não e como removê-los.

Descoberta realmente simples

Este é o código que exibe o seguinte código em seu cabeçalho:

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

Esse é o mecanismo de descoberta usado pelos clientes XML-RPC.  Se você não tem ideia do que isso significa e/ou não integra serviços

como o Flickr ao seu site WordPress, provavelmente é seguro removê-lo com o seguinte código no arquivo de funções do seu tema.

remove_action('wp_head', 'rsd_link');

Windows Live Writer

É por isso que você vê o seguinte código em seu cabeçalho.

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

Se você não usa o Windows Live Writer, esse código é completamente inútil para você e deve ser removido.

remove_action('wp_head', 'wlwmanifest_link');

Gerador do WordPress

Isso é o que exibe o número da versão do WordPress em seu cabeçalho.

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

Ninguém realmente precisa saber a versão exata do WordPress que você está usando, portanto, é seguro remover essa linha de código.

remove_action('wp_head', 'wp_generator');

Links relacionais de posts

Os links pós-relacionais são a razão pela qual esse material é exibido em várias páginas.

<link rel='index' title='Página principal' href='http://www.themelab.com' />
<link rel='start' title='Artigo em um passado distante' href='http://www.themelab.com/hello-world/' />
<link rel='prev' title='A postagem anterior a esta' href='http://www.themelab.com/post-before/' />
<link rel='next' title='The Post After This One' href='http://www.themelab.com/post-after/' />

Ainda não encontrei um motivo real para mantê-los.  Alguns navegadores podem usar esse código para navegar em seu site, embora você provavelmente possa obter o mesmo efeito com um tema bem projetado.  Você precisará de três linhas para eliminar todos eles.

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

Modelo do Functions.php

Para sua conveniência, aqui estão todos eles combinados para facilitar a cópia e a colagem no arquivo functions.php do seu próprio 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', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link');
?>

Na verdade, esse é o arquivo

functions.php inteiro que estou usando em meu novo tema de arquivo de tweets. Se você der uma olhada no código, a tag <head> contém apenas três linhas: a declaração do meta charset, a tag title e o link da folha de estilo.

Uma observação sobre temas lançados

Quando estiver desenvolvendo temas para lançamento, tenha cuidado ao remover alguns desses itens, especialmente os dois primeiros: XML-RPC e suporte ao Windows Live Writer.

O motivo deve ser bastante óbvio, pois alguns de seus usuários provavelmente usarão algo como o Windows Live Writer e voltarão a lhe pedir suporte quando não conseguirem descobrir por que ele não funciona com o seu tema.

Os outros itens, o aviso do gerador do WordPress e os links de relação de postagem, provavelmente podem ser removidos com segurança em quase todas as situações.

Conclusão

Como eu disse na introdução, não é um grande problema se você não remover esses itens e eu não diria que isso é “obrigatório” em todos os novos sites WordPress que você desenvolver. Se você for como eu e não gostar de linhas de código inúteis, provavelmente vai querer fazer isso de qualquer forma para manter as coisas funcionando da forma mais limpa possível.

Você se lembra de alguma outra função que usa para remover linhas de código desnecessárias do WordPress? Conte-me nos comentários.

Comentários   Deixe uma resposta

  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).

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!