Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

pt-br:Problemas de Cache

As coisas estão indo muito bem. Você descobriu como escrever postagens, como criar algumas categorias e talvez até mesmo instalar novos temas. Então algo acontece. Você faz algumas mudanças em seu tema e quando você vê o seu site WordPress,nada mudou. Sua correção não fixa. Sua mudança não altera nada. Nada muda! Você quer gritar, puxar seu cabelo, a bater em seu computador e xingar.

Segure-se. Acalme-se! Muitos erros são apenas enganos por causa da pressa. Mesmo se você estiver operando com um prazo apertado, tente manter a calma e se conter, a medida que vai proceder. Isso vai ajudar. Se você começar a ficar tenso, ou frustrado, simplesmente se levante e se afaste por alguns minutos. Às vezes, tudo que é necessário é um ar puro, descansar os olhos para poder detectar a falta de um ponto e vírgula, ou uma marca extra, ou perceber que a solução é muito mais simples do que se pensava inicialmente.

O problema pode ser com o WordPress, pode ser seu banco de dados, pode ser com o servidor, ou pode ser algo que você fez para estragar tudo, mas a realidade é que muitas das vezes não é nenhuma dessas coisas. O culpado é provavelmente o seu navegador de Internet.

Seja qual for o problema, estamos aqui para ajudar. Vamos analisar os possíveis problemas e soluções para quando você faz uma alteração e não acontece nada.

Cache do Navegador

Você sabia que se supões que o computador torne nossas vidas mais fáceis? Menos complicada? Supõe-se que ele pode poupar tempo e energia e melhorar de fato a sua vida. Não? Bem, talvez não, mas o seu navegador da Internet faz o seu melhor para tentar tornar sua vida um pouco mais fácil.

Quando você visita uma página web, muitas vezes demora um pouco para carregar, certo? Mas a próxima página que você visita no site, não leva o mesmo tempo para carregar. Isso porque, em um esforço para ser útil, o navegador armazena a informação no seu computador para que ele recarregue a partir do seu computador, não a partir do próprio site. Isso é chamado de cache e se destina a acelerar a sua navegação na Internet.

O problema acontece quando você faz uma pequena alteração para o seu site e o navegador não o reconhece como uma mudança significativa, de modo que recarrega a mesma página. A solução é limpar ou esvaziar o cache do seu navegador.

Esvaziando o Cache do Navegador

Normalmente, para ver as alterações na sua página, você clica no botão Atualizar ou Reload na barra de ferramentas do navegador ou pressiona a tecla F5 no seu teclado. Em muitos casos, isso simplesmente recarrega a página sem limpar o cache do navegador. Aqui estão algumas técnicas para limpar o cache do navegador assim que você vai ver as alterações quando recarregar sua página.

M;icrosoft Internet Explorer:

  1. Mantenha pressionada a tecla SHIFT e clique no botão Atualizar na barra de ferramentas no menu.
  2. Para Limpeza Total: Se você está tendo problemas de limpeza do cache, o jeito é forçá-lo escolhendo no menu Ferramentas > Opções da Internet> Arquivos temporários. Clique em Excluir arquivos temporários. Marque a caixa Todos para excluir todos os arquivos de internet, o que vai fazer limpar suas senhas armazenadas também,
Mozilla Firefox
  1. Mantenha pressionada as teclas CTRL+SHIFT+R.
  2. Para Limpeza Total: Escolha Ferramentas > Opções > Privacidade > Cache e clique Limpar....
Netscape 
Vá em Editar > Preferências > Avançado. Escolha "Cache" e clique "Limpar memoria do Cahce" e "Limpar disco de cache".
Mozilla 1.x e mais modernos 
Vá em Editar > Preferências > Avançado e clique "Cache" e "Limpar Cache".
Opera 
Vá em Editar > Arquivo > Preferências > Histórico e Cache e clique "Cache".
Safari
Vá em Safari > Redefinir Safari e clique em Redefinir para confirmar ou vá em Safari > Esvaziar Cache.
Diversos
Cada navegador pode ter uma forma de impedir ou minimizar o cache de páginas da web. Verifique a documentação de seu navegador da Internet para saber como impedir de armazenar ou destaivar o recurso de cache.
cb-help.png
Artigo parcialmente traduzido ou que precisa de tradução
Este documento está parcialmente traduzido ou precisa ser traduzido. Toda a tradução é feita por voluntários e você pode ser um deles.
ParticiparArtigos para traduzirFórum de SuporteTodos os Artigos

A WordPress Cache Plugin

Some WordPress plugins also add cache functionality to your blog. This helps your blog load faster because WordPress can retrieve the pages of your blog from the cache instead of generating them all over again.

All good cache plugins will clear the cache when a post, page, or comment is published. However, if you make other changes (e.g. to your theme), the cache may not be cleared and the old version may still appear. In this case, check the plugin's instructions to find out how to clear its cache.

Note that WordPress does not come with a cache by default, so the above would only apply if you installed a cache plugin yourself.

Check Your Source

You know, even the very best web page designers, developers, and programmers screw up. It's the little details, the forgotten semi-colon, the misspelled tag, the lack of attention to a detail that screws things up. If the best do it, then it's very possible you have overlooked a little detail. And if you did, well, welcome to the club. It's a part of the process. Let's look at some of the most commonly overlooked details that happen when you aren't paying attention.

Check the Address

Is the name and folder for the file you "fixed" the same as the one you are viewing? Look at the following two addresses (URLs).

  • wordpress/wp-content/themes/yourtheme/style.css
  • test/wordpress/wp-content/themes/yourtheme/style.css

In this case, you can probably see the difference, but when viewed in an address bar or in a text editor, you might miss the word test that sets the folder.

Pay very close attention to the difference between style1.css and stylel.css if you are using different style names, too. The first filename is style followed by the digit one, while the second filename is style followed by a lowercase L. If you are working with different but similar files, make sure you give them distinctive names like style-red.css and style-800.css so you can clearly see the difference.

Check the Template

If you're editing a template, are you sure the page you're viewing is being generated from that template? Remember that many templates have very similar text on them; for example, a post header may appear on a single post page, index page, search page, archive page, and others.

See Template Hierarchy if you're having trouble figuring out which template is in use.

Check Your Upload

When you make a change in a file, it is often on your computer's hard drive and you have to upload the file to your host server in order to view it on the Internet. Did you actually upload it? Did you put it in the right folder? Is it really there? When over-writing the exact same file, it doesn't always do a complete over-write, so consider deleting the original on the host server and then uploading the new version to make sure the right and whole thing is there.

Test Yourself

If you still can't see the changes you made, and the file is in the right place with the right name, and you are sure it's the right file, then go through these steps:

  1. Make a backup of the file you are working on and check that the backup is in a safe place.
  2. Make a big change (such as setting the background in your style.css as #ff0000 or even red).
  3. View the changed web page in your browser. Make sure you clear the cache to be sure you have the new version.
  4. If nothing changes, delete the file (and only that file) from the server and try to view the file again. If nothing continues to change, you and WordPress are looking at completely different files. It's time to get out your detective hat and start tracking down what is going on and where your files went to.
  5. Check your URL settings in your Options Panel and also in the database, and if this continues to be unsolvable, post a note explaining what you've done and what's the result on the WordPress Forum and let the experts step in to help.

Debug It

Programmers use the term debug to describe the process of going through code and finding the little criminal that is messing things up. We're going to look at how to debug your CSS, HTML, and PHP code to help you figure out why you can't see the changes you have made.

When debugging a problem, change only one thing at a time. If you're not sure if the problem is in line 37 or line 40, don't change both lines in one go! First change line 37, and see if that fixed the problem. If not, undo the change you made on line 37 and then make a change on line 40. It's important to undo proposed fixes before trying something else, even if the first attempt doesn't immediately introduce new problems.

Every time you make a change to a file, you run the risk of accidentally making more mistakes. These sorts of things tend to cascade, making debugging an infuriating process. Do one thing at a time.

Debugging CSS

Debugging your style sheet, or your CSS, can be challenging because you have to find the area in the HTML that is causing the trouble and then track that section back to its style in your style.css file. The article on Finding Your CSS Styles will help you find those troublesome sections.

Once you have found the style that is causing the problem, you need to figure out what it is about the style that is causing the problem. Here is a quick checklist of things to consider as you troubleshoot your CSS:

  • Is everything spelled correctly?
  • Is every period, brace, colon and semi-colon in its right place?
  • Are you using the style attribute or declaration correctly?
  • Is there a declaration that shouldn't be in there, like font-weight:x-large? The declaration x-large is used for font-size not font-weight.
  • Do you have spaces in places where they shouldn't be, like inside of a background-image:url ( ' bg.gif ' )? (correct: background-image:url('bg.gif'))

You can find more information to help you debug and troubleshoot your CSS with:

Debugging HTML

Similar to debugging CSS, HTML can also get bogged down with careless little mistakes like misspellings, forgotten closing tags, forgotten < arrows, and other little errors that can send your site into twisted remains.

It is highly recommended that you use one of the HTML Validators available for free on the Internet. Also, Mozilla Firefox has a powerful free add-on (actually bundled with most Firefox installations) called the Web Developers DOM Inspector that will help you validate and fix your website problems very quickly and easily.

Some tips for debugging your HTML/XHTML may include:

  • Improperly nested XHTML, especially in nested lists commonly found in the sidebar.
  • Unclosed tags.
  • Self-closing tags not closed by use of the forward slash (example: <img src="ball.gif" />).
  • Incorrect tag usage.

For more help on debugging your HTML, check out these articles and resources:

Debugging PHP

If you have access to your webserver's error log, take time to check it. PHP usually logs informative errors here when things go wrong. These log messages can sometimes be a little cryptic, but they should always give the line number of the offending piece of code.

Unfortunately, what PHP thinks is the offending piece of code is sometimes not the problem. For example, an unclosed curly brace { may be reported as a problem on some line number way on down in your script. A quick cheat sheet of PHP error messages and their common causes can be found at Common PHP Errors.

To debug your PHP, here are the steps you should follow:

See Where You Are

The die() command is probably the single most useful debugging tool available. die() immediately halts execution of the program, optionally displaying a message of your choosing.

When trying to work through problems, sprinkle die() statements in at key sections of your script, giving each an informative message:

die('Stage One Complete');
die('Disinfribullation Complete');
die('Finished Collating');

Load your program, and see which message (if any) gets displayed. If you see the first message, you know your program got that far without error. You can safely remove (or comment out) that die() command, and re-run your program, to see how much farther it got. Step through your program this way until you've isolated the problem area.

This technique has some limitations, though. First, if nothing is being displayed in your browser, then most likely you have a fatal syntax error somewhere in your script. Check your webserver's error log, if possible. If the script executes completely -- but incorrectly -- and none of your die() messages are displayed, then you've got some more work to do.

See What's What

If things aren't being set as you want them, or stuff isn't happening when you want, you'll likely need to check the value of different variables at different places of your script. Simply pass the variable to a die() command, and you'll be able to see what that variable's value is:

die($user_level);

This will display the value of the variable $user_level, which should reveal the current user's user level.

This technique is fine for some variable types, like boolean and string ("scalar") variables in programmer parlance; but fails for arrays and objects. To see the value(s) of arrays and objects, use the print_r command:

print_r($post);

It will display the value of the $post array in a human-readable format:

Array ( [0] => stdClass Object ( [ID] => 1 [post_author] 
=> 1 [post_date] => 2005-02-16 09:16:46 [post_date_gmt] 
=> 2005-02-16 14:16:46 [post_content] => Welcome to 
WordPress. This is your first post. Edit or delete it, 
then start blogging! [post_title] => Hello world! [post_category] 
=> 0 [post_excerpt] => [post_status] => publish [comment_status] 
=> open [ping_status] => open [post_password] => [post_name] 
=> hello-world [to_ping] => [pinged] => [post_modified] => 2005-04-15 
08:45:42 [post_modified_gmt] => 2005-04-15 13:45:42 
[post_content_filtered] => [post_parent] => 0 [guid] 
=> /?p=1 [menu_order] => 0 ) )

This format allows you to see what each key/value pair is inside the array.

Using print_r() does not stop execution of the program, so it is often necessary to call die() immediately afterwards.

Use print_r() and die() to check the values of your variables through the execution of your script. There's also a var_dump() function which works similarly. Use whichever mechanism you find most informative.

When All Else Fails

If all else fails, know this: You are not alone. We've all been there. To help you get back on track and your site up and running again, check the following resources for more help: