WordPress-利用AJAX 功能实现文章列表赖加载

就像移动端常见功能,用户浏览到接近页面底部时再触发新数据的加载,在wordpress中,可借助 JavaScript 与 WordPress 的 AJAX 功能实现。在wordpress,文件【admin-ajax.php】专门集成AJAX功能。

实现思路:【后端php】构建一个 AJAX 处理函数,用于按需返回文章数据。【前端js】运用 JavaScript 监听滚动事件,当用户滚动到接近页面底部时,发送 AJAX 请求到后端获取新文章数据,再将其追加到页面上。

php代码如下:

<?php
// 添加 AJAX 处理函数
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
add_action('wp_ajax_load_more_posts', 'load_more_posts');
function load_more_posts() {
    $paged = $_POST['paged'] + 1;
    $posts_per_page = 10; // 每页显示的文章数量
    $args = array(
        'posts_per_page' => $posts_per_page,
        'paged' => $paged
    );
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        $articles_by_date = [];
        while ($query->have_posts()) {
            $query->the_post();
            $post_date = get_the_date('Y年n月j日');
            if (!isset($articles_by_date[$post_date])) {
                $articles_by_date[$post_date] = [];
            }
            $articles_by_date[$post_date][] = [
                'title' => get_the_title(),
                'categories' => get_the_category(),
                'permalink' => get_permalink()
            ];
        }
        ob_start();
        foreach ($articles_by_date as $key1 => $values1) {
            ?>
            <article class="card">
                <time class="card-date"><span class="txt-gray"><?php echo $key1 ?></span></time>
                <?php
                foreach ($values1 as $index => $item1) {
                    $is_last = ($index === count($values1) - 1);
                    ?>
                    <div class="card-content">
                        <h2 class="card-title">
                            <a href="<?php echo esc_url($item1['permalink']) ?>">
                                <?php echo $item1['title'] ?>
                            </a>
                        </h2>
                        <ul class="card-line">
                            <?php
                            if ($item1['categories']) {
                                foreach ($item1['categories'] as $item2) {
                                    ?>
                                    <li class="txt-gray">
                                        <a href="<?php echo esc_url(get_category_link($item2->term_id)) ?>">
                                            <?php echo $item2->name ?>
                                        </a>
                                    </li>
                                    <?php
                                }
                            }
                            ?>
                        </ul>
                    </div>
                    <?php
                    if (!$is_last) {
                        echo '<hr>';
                    }
                }
                ?>
            </article>
            <?php
        }
        $output = ob_get_clean();
        wp_send_json_success(array(
            'html' => $output,
            'paged' => $paged
        ));
    } else {
        wp_send_json_error('No more posts found.');
    }
    wp_die();
}
// 注册 AJAX URL
function enqueue_ajax_scripts() {
    wp_register_script('ajax-script',get_template_directory_uri().'/js/ajax/load-more-posts.js',array('jquery'),filemtime(get_template_directory().'/js/ajax/load-more-posts.js'),true);
    wp_enqueue_script('ajax-script');
    wp_localize_script('ajax-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'paged' => 0
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_scripts');

js代码如下:

//确保在页面 DOM 结构完全加载完后执行。function ($) 中的 $ 是 jQuery 别名,这样在函数内部可直接用 $ 来调用 jQuery 的方法,不必每次都写 jQuery。
jQuery(document).ready(function ($) {
    var is_loading = false;
    var paged = ajax_object.paged;
    // window 对象的 scroll 事件绑定了一个处理函数。当用户滚动浏览器窗口时,这个函数就会被触发。
    $(window).scroll(function () {
        //$(window).scrollTop():指的是当前窗口的垂直滚动距离,也就是从文档顶部到窗口顶部的距离。
        // $(window).height():代表当前浏览器窗口的可视高度。
        // $(document).height():表示整个文档的高度。
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 200 &&!is_loading) {
            is_loading = true;
            $.ajax({
                url: ajax_object.ajax_url,
                type: 'POST',
                data: {
                    action: 'load_more_posts',
                    paged: paged
                },
                success: function (response) {
                    if (response.success) {
                        //将服务器返回的 HTML 内容追加到页面中 class 为 site 的元素中。
                        $('.site').append(response.data.html);
                        //更新当前页码为服务器返回的新页码。
                        paged = response.data.paged;
                        is_loading = false;
                    } else {
                        is_loading = true; // 没有更多文章,停止加载
                    }
                },
                error: function () {
                    is_loading = false;
                }
            });
        }
    });
});