Well i figured it out somehow. There were two causes to that issue:
-
tax_query
array values cannot be empty. it either the array keys are populated, or there shouldn’t be an array at all. -
I don’t know why, but giving
author
a number didn’t work. I’ve changed it to'author__in' => array($author)
and it worked.
The fixed code altogether:
function bayadaim_ajax_fetch_posts(){
$template = $_POST['template'];
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
$tax = $_POST["tax"];
$term = $_POST["term"];
if( !empty($_POST["tax"]) || !empty($_POST["term"]) ){
$tax_query = array(array(
'taxonomy' => $tax,
'field' => 'slug',
'terms' => $term,
),
);
}else{
$tax_query = null;
}
$meta = $_POST["meta"];
$author = $_POST["author"];
$orderby = $_POST["orderby"];
$order = $_POST["order"];
$post_type = (!empty($_POST["post_type"]) ? $_POST["post_type"] : "post");
header("Content-Type: text/html");
$args = array(
'meta_key' => $meta,
'orderby' => $orderby,
'order' => $order,
'posts_per_page' => $ppp,
'tax_query' => $tax_query,
'author__in' => array($author),
'offset' => $offset,
'post_status' => 'publish',
'post_type' => $post_type
);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
if ( $template == 'row' ) {
include( locate_template( 'content-post_in_row.php', false, true ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.
}elseif( $template == 'list' ){
include( locate_template( 'content-post_in_listing.php', false, true ) ); //by using include(locate_template()) combination i keep child-theme functionality while still passing variables to included file.
}
endwhile;
else :
if ( !empty($loop) ) print_r($loop); //for debugging
endif;
exit;
}
add_action('wp_ajax_nopriv_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts');
add_action('wp_ajax_bayadaim_ajax_fetch_posts', 'bayadaim_ajax_fetch_posts');
Any suggestions for how to make the code more elegant and efficient are welcomed.