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

Como corrigir a contagem de categorias e comentários após a importação do WordPress

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Você está percebendo uma contagem incorreta de comentários após importar seu site WordPress?

A importação de um site do WordPress usando o importador integrado pode, às vezes, bagunçar a contagem de comentários do WordPress.

Neste artigo, mostraremos a você como corrigir a contagem de categorias e comentários após a importação do WordPress.

How to Fix category and comment count after WordPress import

O que causa o erro de contagem de categoria e conteúdo no WordPress?

Quando você importa seu site do WordPress usando o importador integrado, às vezes ele pode mostrar uma contagem de comentários imprecisa ou nenhuma.

Embora todos os comentários do WordPress sejam importados com segurança e estejam visíveis na área de administração, suas postagens mostrarão uma contagem incorreta de comentários em seu site. Esse mesmo erro de importação também pode afetar a contagem de categorias e a contagem de taxonomias personalizadas.

Fix comment count preview

Como você notou na captura de tela acima, após a importação, nossa contagem de comentários e de categorias está mostrando 0 em vez do número real.

Dito isso, vamos dar uma olhada em como corrigir esse problema e ver a contagem precisa de comentários no WordPress.

Como corrigir a contagem de categorias e comentários no WordPress

Primeiro, você precisa criar um backup completo do WordPress em seu site. Você deve fazer isso sempre que fizer uma alteração importante em seu site.

Recomendamos o uso do Duplicator porque ele é o plug-in de backup do WordPress mais abrangente do mercado.

Para obter mais detalhes, consulte este guia sobre como fazer backup do seu site WordPress com o Duplicator.

Depois de fazer o backup, vamos passar para a próxima etapa.

Em seguida, abra um editor de texto simples, como o Bloco de Notas, e simplesmente copie e cole o código a seguir:

<?php
include("wp-config.php");
$myConnection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD)) {  die('Could not connect: ' . mysqli_error());  }
if (!mysqli_select_db($myConnection, DB_NAME)) {  die('Could not connect: ' . mysqli_error());  }
 
$result = mysqli_query($myConnection, "SELECT term_taxonomy_id FROM ".$table_prefix."term_taxonomy");
while ($row = mysqli_fetch_array($result)) {
  $term_taxonomy_id = $row['term_taxonomy_id'];
  echo "term_taxonomy_id: ".$term_taxonomy_id." count = ";
  $countresult = mysqli_query($myConnection, "SELECT count(*) FROM ".$table_prefix."term_relationships WHERE term_taxonomy_id = '$term_taxonomy_id'");
  $countarray = mysqli_fetch_array($countresult);
  $count = $countarray[0];
  echo $count."<br />";
 mysqli_query($myConnection, "UPDATE ".$table_prefix."term_taxonomy SET count = '$count' WHERE term_taxonomy_id = '$term_taxonomy_id'");
        }
 
$result = mysqli_query($myConnection, "SELECT ID FROM ".$table_prefix."posts");
while ($row = mysqli_fetch_array($result)) {
  $post_id = $row['ID'];
  echo "post_id: ".$post_id." count = ";
  $countresult = mysqli_query($myConnection, "SELECT count(*) FROM ".$table_prefix."comments WHERE comment_post_ID = '$post_id' AND comment_approved = 1");
  $countarray = mysqli_fetch_array($countresult);
  $count = $countarray[0];
  echo $count."<br />";
  mysqli_query($myConnection, "UPDATE ".$table_prefix."posts SET comment_count = '$count' WHERE ID = '$post_id'");
        }
?>

É necessário substituir DB_HOST, DB_USER, DB_PASSWORD pelo host do banco de dados do WordPress (geralmente o host local), nome de usuário e senha do banco de dados.

Você pode encontrar todas essas informações fazendo login no cPanel da sua hospedagem WordPress ou consultando o arquivo wp-config.php usando um gerenciador de arquivos.

Depois de substituir as informações, salve esse arquivo como comments-fix.php em sua área de trabalho.

Agora você precisará carregar esse arquivo no diretório raiz do seu site. Você pode fazer isso usando um cliente FTP ou usando o gerenciador de arquivos no painel de controle da hospedagem na Web.

Para obter mais informações, siga nosso guia passo a passo sobre como usar o FTP para fazer upload de arquivos no WordPress.

Depois de carregar o arquivo em seu site, você precisa abrir o navegador da Web e acessar esse arquivo:

https://example.com/comments-fix.php

Substitua example.com pelo endereço de seu site.

Visitar esse arquivo em seu navegador executará o script que simplesmente percorre suas postagens, categorias, tags, comentários e atualiza a contagem.

Comment count fix

Importante: Quando terminar de corrigir a contagem de comentários no WordPress, você precisará excluir o arquivo comments-fix.php do servidor.

Esperamos que este artigo tenha ajudado você a aprender como corrigir a contagem de categorias e comentários após a importação do WordPress. Talvez você também queira conferir nosso guia sobre como solucionar os erros mais comuns do WordPress e nosso guia definitivo de SEO para WordPress para melhorar suas classificações.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo 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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

22 ComentáriosDeixe uma resposta

  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!

  2. Fitri says

    Mine is not working, all the count from comments-fix.php is appear, but when i go to single page product it still says Reviews(0)

    • WPBeginner Support says

      Your server may be running on a newer PHP version, this code was for php 5.5 and we will certainly take a look into what we can do to update the code.

      Administrador

  3. Peter Edwards says

    I lost most of the tag counts in a recent import – fixed this by bulk editing all the posts which were tagged and clicking update (without any changes). This triggers the tag count to be updated by wordpress core. Not sure if a similar trick would work for comments?

  4. Pare says

    Just using cPanel go to PhpMyAdmin

    Check What is category id (term_id) in table “xxx_terms” and then update count value in column count into the table “xxx_term_taxonomy” where the term_id is equal term_id of xxx_terms table which that category exists on.

    Forexample “uncategory” of product is term_id = 10 and count value is wrong, I update count value to be correct number in table “xxx_term_taxonomy” where term_id = 10. by manual on cPanel – PhpMyAdmin tool.

  5. Cosmin says

    Quick question: when replacing the DB_HOST, DB_USER, DB_PASSWORD and DB_NAME do we need to use “” or ” to enclose those values in? Or do we simply paste the values?
    I tried and I am getting 500 Internal Server Error while accessing the uploaded file

    • Tyler says

      Yes, you do need to include single quotes around those values. Author should update the snippet to reflect that. Also, author forgot to mention that DB_NAME must also be changed.

      Easy to spot, but this tutorial will fail for anyone following the instructions explicitly.

  6. Aeryn Lynne says

    After a disastrous comment import that involved Intense Debate (only thing we could do is import bits of the xml file directly into mysql after obtaining post IDs for nearly a thousand posts,) I’m definitely in need of a quick program like this to correct the count, so thank you!

    If anyone is looking to fix the comment count for one or two posts only though: instead of accessing FTP and mysql, they just need click Edit on one of the comments of the post that needs correction, and then click Update, and the post then updates the comment count for all comments involved in that post.

  7. Edwin Rio says

    hi …

    i have migrated one sito into another (i was using disqus for comments)

    now in my new site, i can see the comments on the comments area but once i activate the disqus plugin the comments are not appearing on the front end article,

    is this solution for my problem as well or my problems its most on disqus side ?

    Thanks !

  8. union says

    hi …
    i have migrated one sito into another (i was using disqus for comments)

    now in my new site, i can see the comments on the comments area but once i activate the disqus plugin the comments are not appearing on the front end article,

    is this solution for my problem as well or my problems its most on disqus side ?

    Thanks !

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.