In my wordpress website I try to display posts after a category click.
This is my JS function :
function loading_posts_categories($) {
$('#categories a').on('click', function (e) {
e.preventDefault();
var category = $(this).data('category');
$.ajax({
type: 'POST',
url: adminAjax.ajax_url,
data: {
action: 'fetch_posts_by_category',
category: category,
},
success: function (response) {
var container = $('#posts-container');
container.hide();
container.html(response.template).fadeIn();
},
error: function (xhr, status, error) {
console.log( xhr.responseText );
}
});
});
};
And this is my php function :
function fetch_posts_by_category() {
if (empty($_POST['category'])) {
wp_send_json_error('Category not provided.');
}
$category = sanitize_text_field($_POST['category']);
$posts = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'category_name' => $category,
]);
ob_start();
//require get_template_directory() . '/template-parts/template-posts-container.php';
get_template_part('template-parts/template-posts-container', null, [ 'custom_posts' => $posts ] );
$template_content = ob_get_clean();
wp_send_json([
'template' => $template_content,
]
);
die();
}
I have this template template-posts-container.php :
<div id="posts-container">
<?php foreach ($custom_posts as $post): ?>
<h2><?php echo esc_html($post['title']); ?></h2>
<div class="post-content"><?php echo wp_kses_post($post['content']); ?></div>
<?php endforeach; ?>
</div>
And this is my template called template-posts (how can I do the link between this template and template-posts-container ?). This is this template who is display on my page.
<?php $categories = get_categories(); ?>
<div id="categories">
<ul>
<?php foreach ($categories as $category) : ?>
<li><a href="#" data-category="<?= $category->slug; ?>"><?= $category->name; ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<div id="years-container"></div>
My problem :
When I dump the posts into my PHP function I get all the posts according to category displayed correctly.
However, the template remains empty. I can’t pass my posts to my template.
Where is the problem ?
Thanks a lot for help
2
Answers
In the template. Saved the problem.
Here is your modify template-posts-container.php temaplte code, You should try