I am trying to make a function and exclude in the post query that way im able to define the id’s in my function but it is only excluding 1 post instead of the 4 it is returning.
any suggestions on how I can go about successfully executing this?
function in the functions.php file
function slider_exclude(){
$exclude_query = query_posts(array('showposts' => 4, 'cat' => 'news',));
foreach($exclude_query as $post_ids){
return $post_ids->ID.',';
}
}
my loop
$args = array(
'post__not_in' => array(slider_exclude()),
'post_type' => 'post',
'posts_per_page' => 15,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1)
);
query_posts($args);
Your PHP is wrong.
function slider_exclude(){
$exclude_query = query_posts(array('showposts' => 4, 'cat' => 'news',));
foreach($exclude_query as $post_ids){
return $post_ids->ID.',';
}
}
Looks like you are trying to build a comma delimited string but that isn’t how return
works. When that foreach
hits the return
the function returns– it ends. Nothing else gets processed.
You need to be building and returning an array, from the look of it.
function slider_exclude(){
$ret = array();
$exclude_query = query_posts(array('showposts' => 4, 'cat' => 'news',));
foreach($exclude_query as $post_ids){
$ret[] = $post_ids->ID;
}
return $ret;
}
Then you will have trouble with this line:
'post__not_in' => array(slider_exclude()),
Because now you will have a nested array. Do this:
'post__not_in' => slider_exclude(),
Or better:
$args = array(
'post_type' => 'post',
'posts_per_page' => 15,
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1)
);
$exclude = slider_exclude();
if (!empty($exclude)) {
$args['post__not_in'] = $exclude;
}
query_posts($args);
That will only add the post_not_in
condition if there is something to exclude.