在同一类别中加载更多帖子 - WordPress + Ajax + Timber

Load more posts in the same category - WordPress + Ajax + Timber

我在 WordPress 中使用 Timber。

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

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

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

但是当我点击按钮 "Load more posts" 时试图在同一类别中显示 post。没有 post 显示。类别有什么问题?

请问有什么帮助吗?

archive.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
));

script.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);
            }
        });
    });
}

functions.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();
}

archive.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 %}

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

function get_news() {
    global $post;

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

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

1) return 客户端按钮的类别 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(类别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) 在服务器上使用它而不是全局 post

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

加法:

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

  1. 从服务器return发送了什么?
  2. 检查您使用 ::get_posts() 得到了什么?
  3. 为什么不使用 get_posts 原生 wordpress api 功能?

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

整理代码: 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); // ??? 
});

进行检查,return 数据并寻找您有“漏洞”的地方