Question

My site cached by "wp-supper cache" plugin and "cloudflare.com"

So my php function to count post views working incorrectly.

I try to use ajax for it but I'm noob with JS code so I can not know where is wrong.

In functions.php I create a simple function:

add_action('template_redirect', 'ajax_activation');
function ajax_activation(){
   //optional 
   wp_enqueue_script( 
      'ajax_script', 
       get_template_directory_uri() . '/js/ajax.js', // path to your js file for ajax operations
       array( 'jquery' ), false
   );
   //end optional
   wp_localize_script( 
      'ajax_script', // the name of your global.js registered file
      'ajax_object', // name 
       array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) // you can add other items for example for using a translated string in javascript/jquery context
   ); 
}

add_action('wp_ajax_get_PostViews', 'get_PostViews');
add_action('wp_ajax_nopriv_get_PostViews', 'get_PostViews');

function get_PostViews() {
$id = isset( $_POST['id'] ) ? $_POST['id'] : false;
$count_key = 'post_views_count'; 
$count = get_post_meta($post_ID, $count_key, true);
if( empty($count) ){ $count = 1; } else { $count++; }
update_post_meta($post_ID, $count_key, $count);
}

Code in ajax.js file:

var postID = $(".view_detail").attr("id");
jQuery.ajax({
    type: "POST",
    url: ajax_object.ajaxurl, // this is the object you defined in function.php
    data: {
       action: 'get_PostViews', // the name of your function
       id: postID // you can store it in html attribute for an easy access like: jQuery(element).attr('id');
    },
    success: function (result) {
    }
});

The page.php in my theme:

<div id="<?php the_ID(); ?>" <?php post_class('view_detail'); ?>>

Please tell me how can I do it work? Thank you very much!

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top