首页 > 解决方案 > 如何在 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 中做什么,但我不知道怎么做。

标签: phpajaxwordpressfunction

解决方案



推荐阅读