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.
Jquery
$(document).ready(function(){
$("a").addClass("external");
$("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
});
});
});
functions.php
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
}
content.php
<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 ?
update_post_meta()
function will automatically insert the meta value if the meta key doesn't exist yet. No need to calladd_post_meta()
manually.