I’m new to Sage so excuse any ignorance and poor practices on my part.
I’m currently testing a custom post type list with AJAX filtering. I can get the query correctly and output data for each post however I’m now at a stage where I want to use a blade partial for each post.
I have seen a few others ask this question but I can;t seem to get it working in my own context. Here’s my current function, the $responsenear the bottom is what is output -
add_action('wp_ajax_get_ajax_posts', __NAMESPACE__ . '\\get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', __NAMESPACE__ . '\\get_ajax_posts');
function get_ajax_posts() {
// Query Arguments
if(isset( $_POST['categoryfilter'] ) ) {
$args = array(
'post_type' => array('new'),
'post_status' => array('publish'),
'post_type' => 'new',
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'tax_query' => array(
array(
'taxonomy' => 'industry_category',
'field' => 'term_id',
'terms' => $_POST['categoryfilter'],
)
),
);
} else {
$args = array(
'post_type' => array('new'),
'post_status' => array('publish'),
'post_type' => 'new',
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC or DESC
);
}
// The Query
$ajaxposts = new \WP_Query( $args );
$response = '';
// The Query
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response = App\template('partials/content-cards');
}
} else {
$response = 'error';
}
echo $response;
die; // leave ajax call
}
Again, sorry if I’m being dense but have been stuck on this a little while now and feel like there’s an easy solution, I’m just not using right syntax.
There are a couple issues here that could be contributing to your problem:
When you call template you’re passing only a the name of your template. You have to pass data in order for the template to have anything to render. i.e. App\template('partials.content-cards', ['some_variable' => $that_variables_data])
Every iteration of your loop is overwriting the $response variable because you keep reassigning the output of template(). If you want to concatenate, you could using something like .= instead of =.
Usually we use dot notation when specifying partials, i.e. App\template('partials.content-cards'). I think Blade should be capable of understanding /, but using the dot is generally a little safer.
Thank you. Will try this out. I forgot to add that currently this function is in app/setup.php. Could that also be causing an issue, Is there a better working practice? I have the AJAX running in it’s own JS file that’s been added to the manifest but I wasn’t sure if I was placing this PHP function in a weird place, it seems to run the AJAX fine fine though.
The AJAX is responding with an error. I’ve tried just trying to output a basic html without passing any variable into the template partial as well. Here’s what I currently have -