I'm new to ajax am trying to create a simple hit counter that updates a custom field in Wordpress after the page loads. The page is cached, so any attempts to use PHP alone will not work.

I'd like to simply pass the post ID through ajax to the php file, get the custom field, and update it with the new hit number.

I currently have the following code, but cannot get it to update the custom field. Here's the jquery:

    cache: false,
    type: 'POST',
    data: {PostId: '<?php echo get_the_ID() ?>'}

And the PHP file it calls:

/* Template Name: AJAX  */ 

    $postid = $_POST['PostId'];  // get the hits from AJAX and save it for PHP      

    $hits = (int) get_post_meta($postid, 'hit_number', true);
    $newhits = $hits + 1;
    update_post_meta($postid, 'hit_number', $newhits);

What am I doing wrong? Also, is there a way to include the PHP function in the same page/file to avoid bringing in an external file? I'm concerned that as traffic gets larger, the file will be requested too often.

Thanks for your help!

1 Answer 1

  1. WordPress loads jQuery in NoConflict mode. Do not use $. Use jQuery or one of the other solutions in the Codex.
  2. If that Javascript is in a .js file, that is not going to work. You cannot run PHP in a Javascript file like that, without reconfiguring the server, and the call to get_the_ID would likely fail anyway.
  3. You are directly loading a .php file. That means that WordPress is not being loaded so any attempt to use a WordPress function will not work.

Item #1 and #3 are definitely problems. Item #2 may or may not be.

You should be using the AJAX API for this. Your WordPress functions will be loaded and will work correctly. The examples on the AJAX API Codex page are pretty straightforward. It should not be hard to translate your code to that pattern, but if you have trouble I will edit the answer when I have time.

  • Great help! I've modified the code based on #1. The javascript is directly in the wordpress template file, so it's not in a .js file. And I see that #3 will keep this from working as well. I'm looking at the AJAX API, and I see the example for the admin side, but it doesn't appear to have many examples for the front-end. Could you provide an example that I can follow with the correct hook (if necessary)? Also, I assume this should go in the functions.php file rather than a specific template file? Or does it not matter? Thanks again!
    – dfcode3
    Jun 13, 2013 at 16:19
  • The only change between the admin side and the front end is that you need a wp_ajax_nopriv_* hook to run the callback for users who are not logged in.
    – s_ha_dum
    Jun 13, 2013 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.