There is probably a much easier way to do this. After much trial and error trying to get a postid from a url, I've opted to add the id to the permalink. However I have no idea how the custom value should be updated without a page refresh.


     $("a").attr( "target", "_blank" );

jQuery(document).ready(function($) {
$('.external').click(function(event) {
      // had to add the post id to the permalink in loop as url to postid didn't work
      var currentID = $(this).attr('id'); 
      var data = {
        action: 'my_action',
        whatever: currentID
    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
           //update the custom field value without a page refresh


add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
    global $wpdb; // this is how you get access to the database
       $whatever = intval( $_POST['whatever'] );
       // get number of views if we have any
       $views = get_post_meta($whatever, views, true); 
       // update or add post meta
if(!update_post_meta($whatever, 'views', ($views+1))) {
            add_post_meta($whatever, 'views', 1, true);
    die(); // this is required to return a proper result


<a href="<?php the_permalink(); ?>" id="<?php the_ID(); ?>"><?php the_title(); ?></a>
    <?php echo get_post_meta($post->ID, 'views', true) ?>
    // update the view ?

First, you need to output a response in your my_action_callback() function. That response will be available inside your jQuery success callback: function(response){}. At that point it is just a matter of updating the HTML of the page with the new views count.


function my_action_callback()
    // ...
    echo $views;


jQuery.post(ajaxurl, data, function(response) {
    // $(this) refers to the clicked link.
    // You may use another selector too if needed.
  • getting nothing with – steen Nov 29 '11 at 14:02
  • Could you be a bit more descriptive? Show some code? Any error messages? – Geert Nov 29 '11 at 14:35
  • Thanks Geert. I've didn't have much luck with $(this).text(response); the only thing I've been able to get to work is $('.external').text(response); trying to get $(div.currentId).text(response); do I need to add the id somehow to the function event for it to work? Response is working by the way in alert. – steen Nov 29 '11 at 14:36
  • $(this).text(response); no errors just nothing is happening – steen Nov 29 '11 at 14:39
  • If the response is working, all you need to figure out is the selector for the view count. Showing us the HTML may help. – Geert Nov 29 '11 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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