1

I know how to use include and exclude parameters of the get_posts function but how do I tell get_posts to exclude a document and every child page under it ?

I know that I could collect all the IDs of the child pages using get children() and then append an array of these in the exclude parameter, but is there not a better and faster way ?

  • You'll need to figure out the IDs of all the posts underneath beforehand, but keep in mind that exclusion queries are super expensive, normally it's much faster to ask for more posts than you need and manually filter the posts you don't want in PHP than it is to ask the database to do it. Asking the database to figure it all out is going to be expensive/slow – Tom J Nowell Jan 24 '17 at 19:45
  • @TomJNowell any idea if post_parent__not_in would be more efficient than a separate query to determine the IDs to exclude? – Dave Romsey Jan 24 '17 at 19:48
  • 1
    Any query that says what you don't want will be inefficient as it involves a full table scan. You want to avoid any query parameter with the word not in. A separate query would be more efficient. Always query for what you want, never what you don't want – Tom J Nowell Jan 25 '17 at 1:16
3

I know how to use include and exclude parameters of the get_posts function but how do I tell get_posts to exclude a document and every child page under it ?

You can't, get_posts won't search for child posts if you exclude something, you have to tell it exactly what you want excluded

I know that I could collect all the IDs of the child pages using get children() and then append an array of these in the exclude parameter, but is there not a better and faster way ?

That's almost how you should do it, except:

  • don't use children or get_posts, use WP_Query for both
  • don't use the exclude parameter, ask for more posts than you need then check for it manually in PHP, this will be significantly faster as exclusion makes querys very expensive ( as the number of posts increases, so does the cost of these queries )

Remember, always query for what you want, not what you don't want. When you say you don't want something, the database has to collect every post, filter out those that don't match to create a second data set, then run the query without the exclusion on the new data set. Even if you only want 2 or 3 posts, it loads everything. This is true be it excluding post IDs, posts in a category, posts that have a particular post meta value, etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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