First off, you should consider using using the building WordPress functionality rather than linking straight to a PHP file. Anyone could game that very easily and artificially vote up posts.
To use the wordpress ajax functionality, send your ajax request to yoursite.com/wp-admin/admin-ajax.php, and use standard plugin hooks system.
Tollmanz’s response is right on: your update post meta and get post meat calls aren’t working because the WordPress environment is not loaded in rating.php. Another reason to use admin-ajax.php to handled your response.
Here’s an example:
<?php
add_action( 'wp_ajax_nopriv_wpse26789_action', 'wpse26789_ajax_cb' );
add_action( 'wp_ajax_wpse26789_action', 'wpse26789_ajax_cb' );
function wpse26789_ajax_cb()
{
// Verify the nonce to make sure the request came from an actual page...
if( !isset( $_REQUEST['nonce'] ) || ! wp_verify_nonce( $_REQUEST['nonce'], 'wpse26789_nonce' ) ) die( '-1' );
$post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;
if( ! $post_id ) die( '-1' );
$counter = get_post_meta( $post_id, 'good_post', true );
$counter = absint( $counter );
if( $counter )
{
$counter++;
}
else
{
$counter = 1;
}
update_post_meta( $post_id, 'good_post', $counter );
echo $counter;
die();
}
Then your front end could would have to change a little bit.
Here’s a function you could drop inside the loop on your single.php file:
<?php
function wpse26789_good_bad()
{
global $post;
$count = get_post_meta( $post->ID, 'good_post', true );
?>
<p id="wpse26789_click">Click Here to Vote this Post up</p>
<p>This post has <span id="wpse26789_count"><?php echo strip_tags( $count ); ?></span> votes</p>
<?php
}
Eg. somewhere in single.php insert wpse26789_good_bad()
or insert the code from the function into single.php (except for the global $post
) anywhere inside the loop.
Then you’ll need to change up your javascript a bit. I’ve just hooked into wp_head here to add the javascript to the <head>
section of any singular post.
<?php
add_action( 'wp_head', 'wpse26789_head' );
function wpse26789_head()
{
if( ! is_singular() ) return;
$post_id = get_queried_object_id();
?>
<script type="text/javascript">
var wpse26789_data = {
action: 'wpse26789_action',
post_id: '<?php echo absint( $post_id ); ?>',
nonce: '<?php echo wp_create_nonce( 'wpse26789_nonce' ); ?>',
}
jQuery(document).ready(function(){
jQuery( '#wpse26789_click' ).click(function(){
jQuery.get(
'<?php echo site_url( 'wp-admin/admin-ajax.php' ); ?>',
wpse26789_data,
function( data ){
if( '-1' != data )
{
jQuery( 'span#wpse26789_count' ).html( data );
alert( 'Your Message!' );
}
}
);
});
});
</script>
<?php
}
As a plugin: http://pastie.org/2423993