I have an array, where keys are the post ID's and values are post titles.

$options = [];
$args = array(
    'posts_per_page'   => -1,
    'fields'           => '',
$posts = get_posts( $args );
foreach( $posts as $post ) : setup_postdata( $post );
$options[ $post->ID ] = $post->post_title;
wp_reset_postdata(); endforeach;
return $options;

This array works fine and i can use it in my backend to select posts i wann't to exclude from specific query, but it does not work on frontend, since it excludes only the first post from array.

In query it looks like this:

$posts_to_exclude = ! empty( $settings['posts_to_exclude'] ) ? $settings['posts_to_exclude'] : ' (choose post) '; 

$exclude_posts = implode(", ", $posts_to_exclude);
print $exclude_posts;

And then in WP Query array:

$args = array(
   'posts_per_page' => $settings['posts_count'],
   'cat' => $posts_category,
   'post__not_in' => array($exclude_posts),

I have no idea what i could do wrong. Anyone can save me?

1 Answer 1


simply not "imploding" your array since implode() returns a string and post__not_in accepts an array

  • I found that array prints like this: Array ( [0] => Post Title 1. [1] => Post Title 2 ) It gives me numbers counting from 0 instead of ID, only the value (post_title) is fine. Do you have any idea what is wrong? Aug 26, 2018 at 15:36
  • if that's the content of $post_to_exclude you cannot use it in post__not_in where the array must be an array of IDs Aug 26, 2018 at 15:40
  • That's your array of posts to exclude? You really need IDs, not titles.
    – De Coder
    Aug 26, 2018 at 15:40
  • I need an array of post ID as keys and post titles as Values, for example: 10 => Post Title It need's to be used for Elementor page builder where i select posts to exclude from query in my custom widget. Then i need to take all of these ID's only and exclude these posts from WP Query Aug 26, 2018 at 15:42
  • the problem is that $settings['posts_to_exclude'] is not usable for your needs, I don't know where it comes from so I cannot help you. You can do $IDs=array(); foreach( $exclude_posts as $exclude){array_push($IDs, get_page_by_title($exclude )->ID ); } and then use 'post__not_in' =>$IDs but it's a kind of extra query that can be avoided if the original array would be better formed to fit your needs Aug 26, 2018 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.