I have this function in functions.php:
function voteaza_lucrare()
{
if ( isset($_REQUEST) )
{
$id_post = $_REQUEST['id1'];
$time = current_time('mysql');
$current_user = wp_get_current_user();
$data = array(
'comment_post_ID' => $id_post,
'comment_author' => $current_user->user_login,
'comment_author_email' => $current_user->user_email,
'comment_author_url' => 'http://startut.ro',
'comment_content' => 'Vot ',
'comment_type' => '',
'comment_parent' => 0,
'user_id' => $current_user->ID,
'comment_author_IP' => '127.0.0.1',
'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
'comment_date' => $time,
'comment_approved' => 1,
);
wp_insert_comment($data);
echo $id_post;
}
die();
}
add_action( 'wp_ajax_voteaza_lucrare', 'voteaza_lucrare' );
add_action( 'wp_ajax_nopriv_voteaza_lucrare', 'voteaza_lucrare' );
This function will add a comment to a post, work perfect, but…
I try to use this function in comment-template.php for the link of a button using ajax request:
<div style="float: right;"><a onclick="add_comment('<?php echo $id ; ?>')" href="#" class="button facebook"><font color="#ffffff">Votează această lucrare</font></a></div>
And the function for ajax request is:
<script>
function add_comment(id)
{
jQuery(document).ready(function($) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
url: ajaxurl,
data: {
'action':'voteaza_lucrare',
'id1' : id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
}
</script>
The code add the comment, this is the resolvation if anyone will have the same problem.
It can be done this way.
Then in the ajax request execute your php code to add a comment to your post.
If you are not familiar with using ajax in WP have a look at this simple example.
EDIT :
Notice the slight modification.