我在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' );
此功能会为帖子添加评论,工作完美,但......
我尝试在comment-template.php中使用此函数来获取使用ajax请求的按钮链接:
<div style="float: right;"><a onclick="add_comment('<?php echo $id ; ?>')" href="#" class="button facebook"><font color="#ffffff">Votează această lucrare</font></a></div>
ajax请求的功能是:
<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>
代码添加注释,如果有人遇到同样的问题,这就是解决方案。
答案 0 :(得分:0)
可以这样做。
<?php
$id = get_the_ID();
?>
<div style="float: right;"><a onclick="add_comment('<?php echo $id ; ?>')" class="button facebook"><font color="#ffffff">Votează această lucrare</font></a></div>
<script>
function add_comment(id)
{
//send ajax request in wp with 'id' as data .
}
</script>
然后在ajax请求中执行你的php代码,为你的帖子添加评论。
如果你不熟悉在WP中使用ajax,请看一下这个简单的例子。
编辑:
注意稍作修改。
<script>
function add_comment(id)
{
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>