通过 admin-ajax.php 在 Wordpress 中调用 PHP 函数未更新元信息,但收到成功消息
Calling PHP function in Wordpress through admin-ajax.php not updating meta information, but receive a success message
post_views_count() 旨在使用 ajax 请求更新页面当前 postID 的查看次数,因此它仍然可以工作。
调用时输出已成功调用但在调试时添加了我的视图计数。任何帮助将不胜感激。
仅供参考:这是一个名为课程的自定义 post 类型。
functions.php
内的代码
add_action('wp_ajax_nopriv_post_views_count', 'post_views_count');
add_action('wp_ajax_post_views_count', 'post_views_count');
function post_views_count() {
global $wpdb;
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
exit();
}
内码-courses.php
<script>
jQuery(document).ready(function() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
type: "POST",
cache: false,
url: ajaxurl,
data: {
action: 'post_views_count',
postID: '<?php echo get_the_ID(); ?>'
},
success: function (output) {
console.log("<?php echo get_post_meta(get_the_ID(), 'post_views_count', true); ?>");
}
});
});
</script>
已解决!
发送了对 postID 数据的请求,现在可以在静态缓存页面时跟踪 post 查看次数。
$postID = $_REQUEST['postID'];
post_views_count() 旨在使用 ajax 请求更新页面当前 postID 的查看次数,因此它仍然可以工作。
调用时输出已成功调用但在调试时添加了我的视图计数。任何帮助将不胜感激。
仅供参考:这是一个名为课程的自定义 post 类型。
functions.php
内的代码add_action('wp_ajax_nopriv_post_views_count', 'post_views_count');
add_action('wp_ajax_post_views_count', 'post_views_count');
function post_views_count() {
global $wpdb;
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
exit();
}
内码-courses.php
<script>
jQuery(document).ready(function() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
type: "POST",
cache: false,
url: ajaxurl,
data: {
action: 'post_views_count',
postID: '<?php echo get_the_ID(); ?>'
},
success: function (output) {
console.log("<?php echo get_post_meta(get_the_ID(), 'post_views_count', true); ?>");
}
});
});
</script>
已解决!
发送了对 postID 数据的请求,现在可以在静态缓存页面时跟踪 post 查看次数。
$postID = $_REQUEST['postID'];