我有一个简单的基于PHP的计数器Wordpress函数,每次加载页面时更新用户元数据。
我想做的是只在单击特定按钮时运行此函数。
我的按钮标记
<a class="button" id="interaction-count" href="#">Interaction</a>
我当前的PHP函数(当前运行,并更新用户元,每次页面加载)
function setCvDownloads($postID) {
$count_key = 'download_count';
$count = get_user_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_user_meta($postID, $count_key);
add_user_meta($postID, $count_key, '0');
}else{
$count++;
update_user_meta($postID, $count_key, $count);
}
}
是可能的运行这当interaction-count
按钮点击代替?我想应该涉及到AJAX吧?如果有人能给我指出正确的方向那就太好了
使用Ajax是最好的选择。
<a class="button" id="interaction-count" href="#" onclick="setCvDownloads(<?php echo $post->ID);">Interaction</a>
您需要在该函数中传递post ID,因为您已经将其使用到函数中。
Ajax:确保您的文件路径在Ajax语法的URL中是正确的,否则它将不起作用。
function setCvDownloads(a)
{
$.ajax({
type: "POST",
url: "/savedata.php",
data: "&post_id="+a,
success:function(html)
{
// here you can provide if you need success notifications or as per your wish.
}
});
}
savedata.php
<?php
include('../../wp-config.php'); // Ensure that your wp-config file is connected here correctly.
$post_ID = $_POST['post_id']; // Getting the posted POST ID over ajax here.
$count_key = 'download_count';
$count = get_user_meta($post_ID, $count_key, true);
if($count==''){
$count = 0;
delete_user_meta($post_ID, $count_key);
add_user_meta($post_ID, $count_key, '0');
}else{
$count++;
update_user_meta($post_ID, $count_key, $count);
}
?>
使用jQuery。这段jQuery代码应该可以做到,但是您需要一个PHP文件来捕获请求。
$("#interaction-count").on("click", function(){
$.ajax({
type: "POST",
url: "/somephpfile.php",
data: {},
success: success,
dataType: dataType
});
});
您也可以同步执行,但最好的方法肯定是使用ajax。
所以代码,在简单的js(没有jquery),将是:<input type="button" ... onclick="CallPhpFunction()" />
....
<script>
function CallPhpFunction() {
var xhttp=new XMLHttpRequest();
xhttp.open('POST', 'phpscript.php', true);
xhttp.send('data=somedata&otherData=someotherdata');
}
</script>
在这个例子中,我还展示了如何将数据发送到php脚本,并将其传递给send方法。可以在php脚本中使用$_POST。
为此,您需要在wordpress循环中添加以下代码
<a class="button" id="interaction-count" href="#"
onclick="increaseMyCount('<?php the_ID();?>')">Interaction</a>
<script type="text/javascript">
function increaseMyCount(numb_data)
{
jQuery.ajax({
method: "POST",
url: "<?php bloginfo('url');?>/wp-admin/admin-ajax.php",
data: { postid: numb_data, action: 'setcvdownloads' }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
和在主题文件的functions.php中,您需要编写以下代码
<?php
function setCvDownloads() {
$count_key = 'download_count';
$postID=$_POST['postid'];
$count = get_user_meta($postID, $count_key, true);
if($count==''){
$count = 0;
//delete_user_meta($postID, $count_key);
add_user_meta($postID, $count_key, '0');
}else{
$count++;
update_user_meta($postID, $count_key, $count);
}
echo "Saved";
wp_die();
}
add_action( 'wp_ajax_setcvdownloads', 'setCvDownloads' );
add_action( 'wp_ajax_nopriv_setcvdownloads', 'setCvDownloads' );
?>