php - 如何在 php 中使用 ajax 刷新?
问题描述
我正在尝试在我的网站上制作一个喜欢/拍手/心脏系统并找到了这个网站(https://www.techolac.com/wordpress/how-to-add-likes-to-posts-in-wordpress-without -a-plugin/ ) 教如何做到这一点。我做了一些调整,问题是当我喜欢页面刷新时,我只想刷新数字而不是整个页面。我看到了我可以在 AJAX 中做什么,但我不知道怎么做。
函数.php / Wordpress
// Add buttons to top of post content
function ip_post_likes($content) {
ob_start();
?>
<a href="<?php echo add_query_arg('post_action', 'like'); ?>">
<span class="icon-claps pr-2"><?php echo get_like_count('likes') ?></span>
</a>
<?php
$output = ob_get_clean();
return $output . $content;
}
add_filter('the_content', 'ip_post_likes');
//Get like
function get_like_count($type = 'likes') {
$current_count = get_post_meta(get_the_id(), $type, true);
return ($current_count ? $current_count : '');
}
//Process like
function ip_process_like() {
$processed_like = false;
$redirect = false;
// Check if like
if(is_singular('post')) {
if(isset($_GET['post_action'])) {
if($_GET['post_action'] == 'like') {
// Like
$like_count = get_post_meta(get_the_id(), 'likes', true);
if($like_count) {
$like_count = $like_count + 1;
}else {
$like_count = 0;
}
$processed_like = update_post_meta(get_the_id(), 'likes', $like_count);
}
if($processed_like) {
$redirect = get_the_permalink();
}
}
}
// Redirect
if($redirect) {
wp_redirect($redirect);
die;
}
}
add_action('template_redirect', 'ip_process_like');
问题是,当我确实喜欢页面刷新并且我只想刷新数字而不是整个页面时。我看到了我可以在 AJAX 中做什么,但我不知道怎么做。
解决方案
推荐阅读
- node.js - 用 Jest 测试 NextJS API 中间件
- sql - SQL获取总数并同时使用pivot
- javascript - Typescript 中用于存储任何组件的数据类型
- vue.js - vue-chartJs,无法更新图表
- flutter - 从其他页面返回后关闭模态底页
- html - 使用 Bootstrap Grid 时文本溢出
- cmake - 当同一工具集版本存在多个版本时如何设置默认的 MSVC 编译器版本
- azure - Azure SQL Server 数据库安全不考虑系统当前 IP
- java - 在java中摆脱这个无限循环的方法是什么?
- css - 适合覆盖的 YouTube 视频