I am covering several options in a single file, and loading posts via AJAX so I put in data
attributes query variables: cat
, tag_id
, author
, year
and monthnum
.
Based on what is present or not (if you're on category page the cat
query variable will be some number, but tag_id
will be empty for instance). Now the query looks like this:
$cat = ( isset( $_GET['cat'] ) && '' !== $_GET['cat'] ) ? sanitize_text_field( wp_unslash( $_GET['cat'] ) ) : ''; // Input var okay.
$tag = ( isset( $_GET['tag'] ) && '' !== $_GET['tag'] ) ? sanitize_text_field( wp_unslash( $_GET['tag'] ) ) : ''; // Input var okay.
$year = ( isset( $_GET['year'] ) && '' !== $_GET['year'] ) ? sanitize_text_field( wp_unslash( $_GET['year'] ) ) : ''; // Input var okay.
$month = ( isset( $_GET['month'] ) && '' !== $_GET['month'] ) ? sanitize_text_field( wp_unslash( $_GET['month'] ) ) : ''; // Input var okay.
$author = ( isset( $_GET['author'] ) && '' !== $_GET['author'] ) ? sanitize_text_field( wp_unslash( $_GET['author'] ) ) : ''; // Input var okay.
$post__not_in = ( isset( $_GET['post__not_in'] ) && '' !== $_GET['post__not_in'] ) ? sanitize_text_field( wp_unslash( $_GET['post__not_in'] ) ) : ''; // Input var okay.
$the_query = new WP_Query(array(
'cat' => $cat,
'tag_id' => $tag,
'author' => $author,
'date_query' => array(
array(
'year' => $year,
'month' => $month,
),
),
'post_status' => 'publish',
'post__not_in' => json_decode( $post__not_in, true ),
));
post__not_in
is there to make sure that when I set the home page as a blog page, that I get the correct posts loaded (I had some issues with paged
variable and sticky posts, and this solved that issue).
Now what I haven't found is, will having empty query arguments make the query slower?
Should I base my query arguments based on what variable is empty? Is this better thing to do than to just put it all in one array? Something tells me that this is better because there are less query variables and therefore the query is more specific?
Also when loading posts using AJAX, should I add no_found_rows => 1
, because I'm not using pagination? This should make my query even more faster from what I've read.
Any advice is welcome :)