Having a blog with one post per day from monday to friday, on weekends I need to retrieve last friday post if user click the "today word" or the las thursday post if user click the "yesterday word".
I have registered a query var with this code:
function register_query_vars ($vars) {
$vars[] = 'dia';
return $vars;
}
add_filter('query_vars','register_query_vars');
And I have a link for "today word" that has this url:
http://wordsexample.com/?dia=today;
Then, in the pre_get_posts filter I make the query with the result of a function that return an array with the year, month and day that exactly I need (depending on the day of week and the var queried: today or yesterday).
Well, the problem is that if I hardcode the integer or string values of year, month and day in the set_query_var the query returns de post I want, but if I put variables then the query return all posts from the date passed, and I want only the post of the desired day.
This code runs:
function limit_posts_per_archive_page($query) {
if (!is_admin() && $query->is_main_query()){
if(get_query_var('dia') != ''):
set_query_var('posts_per_page', 1);
set_query_var('posts_per_archive_page', 1);
set_query_var('post_type','post');
set_query_var('post_status','publish');
set_query_var( 'year', 2015 );
set_query_var( 'month', 1 );
set_query_var( 'day', 23 );
elseif (is_home()) :
$query->set('posts_per_page', 10);
endif;
}
}
add_filter('pre_get_posts', 'limit_posts_per_archive_page');
This code doesn't run:
function limit_posts_per_archive_page($query) {
if (!is_admin() && $query->is_main_query()){
if(get_query_var('dia') != ''):
$dies = dies_consulta(); //returns array with the needed date
$anyet = $dies['year'];
$meset = $dies['month'];
$diet = $dies['day'];
set_query_var('posts_per_page', 1);
set_query_var('posts_per_archive_page', 1);
set_query_var('post_type','post');
set_query_var('post_status','publish');
set_query_var( 'year', $anyet );
set_query_var( 'month', $meset );
set_query_var( 'day', $diet );
elseif (is_home()) :
$query->set('posts_per_page', 10);
endif;
}
}
add_filter('pre_get_posts', 'limit_posts_per_archive_page');
I have tested with also with query->set form, but it doesn't matter, if I hardcode the data no problem, if I put the variables it doesn't run.
$query->set('date_query', array(
array(
'year' => $anyet,
'monthnum' => $meset,
'day' => $diet,
),
));
or:
$query->set('date_query', array(
array(
'year' => $dies['year'],
'month' => $dies['mon'],
'day' => $dies['mday'],
),
));
I'm sure I'm missing something but I can't understand why is this different, and no correct, behaviour with variables.
Any idea or suggestion will be very glad.
dies_consulta()
. Have you done avar_dump( dies_consulta() );
to make sure that your function is returning what you expext it to return.