Use wordpress functions in another PHP file

You must put your gallery.php in the same theme folder, where the theme’s functions.php resides. Then add a single line in functions.php:

get_template_part('gallery','');

It’ll include the gallery.php file into functions.php and gallery.php will behave like functions.php.

So, you have to keep in mind that, functions.php file is a file for WordPress and PHP functions. So anything out-of-format without proper formatting may occur error into the whole site – and functions.php is a core file of any theme.

I don’t think it’s impossible using WP_Query() inside a functions.php – but you have to format and place it properly.