I’ve built a custom post filter in WordPress using Ajax.
function filterPublications(filters, filterType) {
filters = JSON.stringify(filters);
$.ajax({
type: 'POST',
url: window.sage.ajax_url,
dataType: 'html',
data: {
action: 'ajax_filter',
publish: 'past',
filters,
posts_per_page: 3,
filter_type: filterType,
},
success: response => {
$('#publications').html( response );
},
})
}
And in functions.php I make a post query to query on the filtered values. What I would like is to return a template part wrapped in html for jQuery to fill the html. But I’m not sure how.
I’ve tried:
$response = '';
if ( $filtered_posts->have_posts() ) {
while ( $filtered_posts->have_posts() ) {
$filtered_posts->the_post();
$response .= '<div class="col-md-4">' . get_template_part('partials/blocks/publications') . '</div>';
}
}
echo $response;
and
$response = '';
if ( $filtered_posts->have_posts() ) {
while ( $filtered_posts->have_posts() ) {
$filtered_posts->the_post();
$response .= '<div class="col-md-4">';
ob_start();
get_template_part('partials/blocks/publication');
$response .= ob_get_contents();
ob_end_clean();
$response .= '</div>';
}
}
echo $response;
Both are not returning the expected response, which is the template part wrapped in the bootstrap column div. How would I do this?