I think there is a small correction in your code, you just passing page number but you have pass category ID also. I’ve added data-category
attribute in load more button. So your archive.twig should like:
<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" data-category="YOUR_CATEGORY_ID_HERE">
<p class="cta__text">Load more posts</p>
</a>
</section>
{% endif %}
Pass data-category
attribute value via your script.js, So script.js code should like:
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,
'get_category' : $(this).data('category'),
},
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);
}
});
});
}
Now receive data-category
attribute value in server side like get_page
, So your functions.php code should like:
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'];
$context['get_category'] = isset($_POST['get_category']) ? $_POST['get_category'] : '';
$context['posts'] = Timber::get_posts(array(
'post_type' => 'post',
'post_status' => 'publish',
'category__in' => array($context['get_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($context['get_category'])
)));
if($count <= $context['get_page'] * 10) $context['ended'] = 'ended';
Timber::render( 'bloc_news.twig', $context );
die();
}