Always using the same ARRAY on different querys
-
16-10-2019 - |
Question
I have a function that returns an array os posts ids.
At the moment, everytime i have a query i have to to this:
$ids = agendados();
query_posts(array('post__not_in' => $ids );
Is there a way to maintain the array by calling that on header.php and use this array everytime a do a query_posts?
I think that doing on my way its a overload of querys..
Thanks m8s Sorry about my poor english
Solution
I don't like using categories for this, as they are supposed to be semantic terms. I do, however, like the idea of the global array. Instead of creating a new query directly, I will filter it through a function that will add the results to a global array and return the results:
I add this to functions.php:
function nt_globals($args){
global $used;
$defaults = array(
'post__not_in' => $used,
);
$query = wp_parse_args( $args, $defaults );
$queryObject = new WP_Query($query);
foreach ($queryObject->posts as $item):
$used[] = $item->ID;
endforeach;
return $queryObject;
}
Then I call the function whenever I want a query:
$queryObject = nt_globals('posts_per_page=1');
while ($queryObject->have_posts()):
$queryObject->the_post();
the_title();
endwhile;
OTHER TIPS
I would actually recommend a different approach:
Create a special category for this set of posts (for example: 'Not in Loop'). Then, when you call query_posts()
you can exclude posts based on that category.
However, if you want to stick with your original functionality ... add a function to wp_head
that sets your array of IDs and then reference that as a global variable whenever you call query_posts()
:
function ignore_ids() {
$ignore_ids = agendados();
}
add_action('wp_head', 'ignore_ids');
Then use:
global $ignore_ids;
query_posts( array('post__not_in' => $ignore_ids) );
im doing something wrong
here is the code:
function agendados() {
global $wpdb;
$ids = array();
$todaysDate = date('Y-m-d H:i:s');
$hoje = strtotime($todaysDate);
$query = "SELECT post_date, ID from $wpdb->posts WHERE post_status='publish'";
$posts = $wpdb->get_results($query);
if ($posts):
foreach ($posts as $post) {
$data_post = $post->post_date;
$str = strtotime($data_post);
if ($str < $hoje) {
$ids[] = $post->ID;
}
}
endif;
return $ids;
}
add_action('wp_head', 'agendados');
then:
global $ids;
$args = array (
'post__not_in' => $ids,
'showposts' => 30,
'order' => ASC,
);
global $post;
$posts = get_posts($args);
if ($posts) {
foreach ($posts as $post) {
setup_postdata($post);
$data = get_the_date('Y-m-d');
echo $data;echo '<br/>';
}
}
the $ids array didn't contain anything :/