首页 > 解决方案 > 加载更多相同类别的帖子 - WordPress + Ajax + Timber

问题描述

我在 WordPress 中使用 Timber。

我正在尝试使用"Load more posts"按钮创建帖子列表。

当用户单击按钮时,我想显示 10 个相同类别的帖子并加载 10 个其他相同类别的帖子"Load more posts"

当类别之间没有区别时,一切正常。按钮"Load more posts"工作正常。显示 10 个帖子。

但是当我单击按钮时尝试显示同一类别的帖子时"Load more posts"。没有帖子显示。类别有什么问题?

请问我可以帮忙吗?

存档.php

$category = get_the_category($post->ID);
$category = $category[0]->cat_ID;

$context['posts'] = Timber::get_posts(array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category__in' => array($category),
    'posts_per_page' => 10,
    'paged' => 1,
    'has_password' => FALSE
));

脚本.js

function load_more_news() {
    var page = 1;

    $(document).on('click', '#load-more-news', function(e) {
        e.preventDefault();
        page++;

        $.ajax({
            type: 'POST',
            url: '/wp-admin/admin-ajax.php',
            dataType: 'html',
            data: {
                'action' : 'get_news',
                'get_page' : page
            },
            success: function(data) {
                if($('<div></div>').html(data).find('.archive__item.ended').size() > 0) $('#load-more-news').parents('.cta').remove();
                else $('#load-more-news').parents('.cta').show();
                $('#archive__list').append(data);
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
}

函数.php

add_action( 'wp_ajax_nopriv_get_news', 'get_news' );
add_action( 'wp_ajax_get_news', 'get_news' );
function get_news() {
    global $post;

    $context = Timber::get_context();
    $context['get_page'] = empty($_POST['get_page']) ? 1 : $_POST['get_page'];

    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;

    $context['posts'] = Timber::get_posts(array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'category__in' => array($category),
        'posts_per_page' => 10,
        'paged' => $context['get_page'],
        'has_password' => FALSE
    ));
    $count = count(Timber::get_posts(array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'category__in' => array($category)
    )));

    if($count <= $context['get_page'] * 10) $context['ended'] = 'ended';

    Timber::render( 'bloc_news.twig', $context );

    die();
}

存档.twig

<section class="archive">
    <p class="archive__title h-headline text-size-l">In the same thematic</p>
    <div id="archive__list" class="archive__list">
        <article class="post">
            ...
        </article>
    </div>
</section>

{% if posts|length >= 10 %}
<section class="cta">
    <a href="#" id="load-more-news">
        <p class="cta__text">Load more posts</p>
    </a>
</section>
{% endif %}

标签: ajaxwordpresstimber

解决方案


老实说,很难理解你,但在我看来,你的问题是你一直在指向一个全球性的帖子

function get_news() {
    global $post;

你需要明确请求类别这是什么意思,我会解释

您需要将 id 类别传输到服务器,而不是使用全局 $post。算法如下:

1)将类别ID返回到客户端上的按钮

<button data-cid="{category_id}">Load more posts</button>

或类别的父元素中的某处

<div class="category" data-cid="<?php print $category_id; ?>">
        <!-- 10 posts -->
        <article class="post">...</article>
        ....
        <button>Load more posts</button>
</div>

2)点击按钮后,获取这个СID(category id)并发送给服务器

function load_more_news() {
    var page = 1;

    $(document).on('click', '#load-more-news', function(e) {
        let $el = $(this); // of e.currentTarget;
        e.preventDefault();
        page++;

        $.ajax({
            type: 'POST',
            url: '/wp-admin/admin-ajax.php',
            dataType: 'html',
            data: {
                'action': 'get_news',
                'get_page': page,
                'cid': $el.data('cid') // CID or $el.parents('[data-cid]').data('cid');
            },
            success: function(data) {
                if ($('<div></div>').html(data).find('.archive__item.ended').size() > 0) $('#load-more-news').parents('.cta').remove();
                else $('#load-more-news').parents('.cta').show();
                $('#archive__list').append(data);
            },
            error: function(data) {
                console.log(data);
            }
        });
    });
}

3)在服务器上使用它而不是全局帖子

'category__in' => array($_POST['cid'])

添加:

什么意思:当我点击“加载更多帖子”按钮时。没有帖子显示。?

  1. 服务器返回什么?
  2. 检查你用 ::get_posts() 得到了什么?
  3. 为什么不直接使用原生 wordpress api 函数的get_posts呢?

检查和调试所有到达服务器并返回的数据

组织您的代码: 1.) 将 ajax url 发送到客户端

wp_register_script('your-script', PLUG_URL.'your-script.js', array('jquery'), filemtime(  PLUG_DIR.'your-script.js' ), true);
   
wp_localize_script('your-script', 'glb',
    array(
        'ajax_url' => admin_url('admin-ajax.php')
    )
);

并使用它并使用它而不是带有 jquery 的 $.post 功能的硬核(推荐)

let payload = {
  page: 2
}
$.post(glb.ajax_url, {action: 'get_news', data: payload, function(e) {
 ....
});

2.)检查服务器的内容

function get_news() {
     wp_send_json($_POST['data']);
}
$.post(glb.ajax_url, {action: 'get_news', data: payload, function(e) {
     console.log(e); // {page: 2}
});

function get_news() { 
    if(!isset($_POST['data'])) {
      wp_send_json_error();
}
$data = $_POST['data'];

$posts = get_posts( array(
        'numberposts' => 10,
        'post_status' => 'publish',
        'category__in'    => [$category],
        'orderby'     => 'date',
        'order'       => 'DESC',
        'post_type'   => 'post',
        'paged' => $data['page']
    ));
  wp_send_json($posts);
}
$.post(glb.ajax_url, {action: 'get_news', data: payload, function(e) {
   console.log(e); // ??? 
});

进行检查,返回数据并寻找您的“漏洞”


推荐阅读