Welcome to WPSE.
First you need to sort out, WHERE you want to execude your php code.
Frontend? Backend? Login Page?
In case it is backend related, add your code via a filter in your functions.php of your theme.
In case it is frontend code, add it
1) either via a filter
2) or to your theme's template file.
From what I can see of your code, you need to know the "WP_Query" object and some awareness of where to put your code. The WP_Query Object is an internal WordPress function, which makes it easier to query the database and get the results.
To add some PHP code to your backend via a filter you can do:
// Do something with the $args/whatever is being passed in here.
// some of your code..
NAME_OF_THE_FILTER references to the place/where you might want to add your code. Please google for WordPress filters to learn more.
In case you want to output your code on the frontend, just copy a template file like "page.php" rename to "page-mycustomwhatevername.php" and add the code to that file, select it in the backend for that page. That way it will be output on the frontend.