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

问题描述

我在wordpress中使用Timber。

我正在尝试使用const copiedArray = [3,2,1]; const ref = copiedArray; const swapped = copiedArray.sort(); console.log(copiedArray); console.log(ref); console.log(swapped);按钮创建帖子列表。

用户单击按钮"Load more posts"

时,我想显示10个相同类别的帖子并加载10个其他相同类别的帖子

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

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

请给我一些帮助吗?

archive.PHP

"Load more posts"

script.js

$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
));

functions.PHP

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

archive.twig

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','paged' => $context['get_page'],'has_password' => FALSE
    ));
    $count = count(Timber::get_posts(array(
        'post_type' => 'post','posts_per_page' => -1,'category__in' => array($category)
    )));

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

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

    die();
}

解决方法

说实话,很难理解您,但是在我看来,您的问题是您一直在指向全球性职位

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(类别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网址发送给客户端

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,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,function(e) {
   console.log(e); // ??? 
});

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