I have a .php page in the theme root to check the data of one CUSTOM form.
After receiving this data I need to do a query in a custom mysql table, so I need $wpdb, but I can’t use it directly (or doing global $wpdb
) because it is a phisical .php file, so the rewrite rule will not affect the request (the request is not passed to index.php because the file exists).
So In this case how can I create an object $wpdb?
Thanks
First of all you probably created an isolated file that is not under the umbrella of WP files. That’s why you are not getting $wpdb. I guess you may not following the general rules/conventions of theme development. my question is now how are you accessing the file?
whatever, if you include the wp_config.php in your file, you will get the $wpdb in your file.
considering in a directory under themes directory, here is how you include/require the file
you may need to alter the path based on your system.
To see how WordPress initialize it, see wp-includes/load.php, line 326.
First, notice what user HungryCoder is saying is correct:
your file, is not being liked to WordPress
One possible solution, that will work on your dev, and Linux servers is:
Excellent solution is:
function
Since immediately after solving this issue begins a new one – where to PUT the initialization (it’s simple, but still if you don’t know this, you may do some nasty things instead – like trying to modify
wp-db.php
). The answer is kind of implicitly hidden in @sorich87’s answer, so just let’s add it here explicitly:Create
db.php
script in your ‘wp-content/’ folder.Also, for more clean initialization than just throwing around globals, see https://stackoverflow.com/a/5418972