Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
Count WordPress Post view onClick using AJAX

How can I count post views of my WordPress posts when click on a button using AJAX?

Currently it's counting the post view whenever I refresh the page, I want to call tha funtion with ajax.

Please check the code I am currently using to show post view count

Inside the functions.php

if ( ! function_exists( 'count_views' ) ) :    
// Get the value of view
function count_views($postID) {   
    
    $count_key = 'wpb_post_views_count';    
    $count = get_post_meta($postID, $count_key, true);    
    
    if($count ==''){
        $count = 1;        
        delete_post_meta($postID, $count_key);        
        add_post_meta($postID, $count_key, '1');    
    } else {        
        $count++;        
        update_post_meta($postID, $count_key, $count);    
    }
}
endif;

Then on single.php I have called the funtion count_views with get_the_ID();

<?php count_views(get_the_ID()); ?>

To retrieve the view count I have used:

<li>
<i class="fa fa-eye"></i>                            
<?php
if (get_post_meta(get_the_ID(), 'wpb_post_views_count', true) == '') {
    echo '0';
} else {
    echo get_post_meta(get_the_ID(), 'wpb_post_views_count', true);
};
?>                             
</li>

How can I call the count_views(get_the_ID()) funtion using javascript Ajax call.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You'll need to add actions to your functions.php file for WordPress. You can then designate callback functions that return the data you are looking for. PHP code below:

// You add two actions here, so it can be accessed from outside the WP CMS
add_action( 'wp_ajax_project_get_post_count', 'project_get_post_count_callback' );
add_action( 'wp_ajax_nopriv_project_get_post_count', 'project_get_post_count_callback' );

function project_get_post_content_callback() {

  if(!empty($_POST['ID'])){
    $postID == $_POST['ID'];
    $count_key = 'wpb_post_views_count';    
    $count = get_post_meta($postID, $count_key, true);
    $response['views'] = $count;
    if($response['views'] ==''){
        $response['views'] = 0;
    }
    wp_send_json( $response );
  }
}

Once you have that setup, in javascript you need to do an AJAX post, passing the action name using the action attribute in POST. This below will get you mostly there. You'll need to format it correctly to be able to get your data. This example is also in jQuery, vanilla JS will be different. JS code below:

$.ajax({
    type: 'POST',
    url: ajaxfullurl,
    data: {
        'action': 'project_get_post_count',
        'ID':<YOURIDHERE>
    }
});

The last piece you'll need is the AJAX URL (ajaxfullurl). WordPress provides a way to get that. This is the PHP code that you'll need to extract the URL for AJAX calls on your WordPress website.

echo admin_url('admin-ajax.php');
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda