I use Timber with WordPress.
I'm trying to create a list of posts with a "Load more posts"
button.
I would like to display 10 posts of the same category and to load 10 others posts of the same category when the user click on the button "Load more posts"
All work fine when there is no distinction between categories. The button "Load more posts"
work fine. 10 posts are display.
But when I try to display posts in the same category when I click on the button "Load more posts"
. No post are display. What's wrong with category ?
Can I have some help please ?
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 %}