filter default query to show just selected level of child pages in wordpress

So it looks like get_ancestors() is the function you need to be able to figure out what ‘level’ something is. The number of results returned from get_ancestors corresponds to your ‘level’ number, with 0 results meaning parent page.

And so the problem you have is that this number isn’t available as a query argument. Therefore, perhaps the simplest option would be to store this as a meta field against all your pages when they’re saved. You could achieve this with a simple hook, like:

add_action('save_post', 'hafiz_update_level_number', 10, 2);
function hafiz_update_level_number($postID, $post) {
   if ($post->type == 'page') {
        update_post_meta($postID, 'hafiz_level_number', get_ancestors($postID)) ;
   }
}

Now don’t need to have the if ($level == ?) code, you just make sure you have a number where 0 is ‘parent’ and 1 is level 1, 2 is level 2, etc. and you can make your query work something like this:

$query->query_vars['meta_key'] = 'hafiz_level_number';
$query->query_vars['meta_value'] = $levelNumber;

You may have to edit this for how you’re using this $query object, but hopefully you get the general idea here.

Note you have the obvious problem that this new value is not set unless a post has been saved or updated after you install this hook, so you will need to either manually open and save every page, or write a quick script to run once which loops through every page and sets this value for every page.

Hope that’s helpful. This code is untested but the intention is to outline a way you can write the complete code you need to answer your question. Please respond with any questions