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!
I’ve spotted some errors here:
Take a look here jQuery.ajax() .
To use ajax within WordPress follow these steps:
retrieved
Enabling ajax
The best way to accomplish that ( in my opinion ) is:
Declare function
jQuery/Javascript
I guess you are using this function for all posts in a loop, you can call ajax once to do the work for all posts.
For example i want to retrieve with ajax the titles of my posts:
HTML
jQuery
PHP
Hope it helps, if something is not clear feel free to ask
Update
According to your question updates, change this:
with this:
single.php
functions.php
ajax.php
single.php //post views
functions.php
ajax.php