Using WordPress WPDB in standalone PHP script?

There may be many cases while developing a website with WordPress, like if you are making any custom page without including wp_header and you want to use WordPress databse queries then the best choice is to use WPDB. If you are usgin WordPress WPDB in standalone PHP script or you want to use WordPress WPDB in you standalone PHP script then you need to know about WPDB class and you need to know how to use it in a standalone script.

What is WPDB?

WordPress has a class called wpdb, which contains a lot of functions to interact with database. Its main purpose is to provide an better interface with the WordPress database, but it can also be used to communicate with any other appropriate database. The code you need to use for being able to use this script in your PHP script with WordPress.

How to use WPDB outside WordPress?

Use the code below to load minimal version of WordPress which include only core functions and includes WPDB. This is fast and light weight also. Put the following code on top of your PHP file.

define( 'SHORTINIT', true ); // tell WordPress to load only core files.

require( '/path/to/wp-load.php' ); // Load WordPress

Things not to do.

Warning: Methods in the wpdb() class should not be called directly. Use the global $wpdb object instead!


Sahil Ahlawat

I am a Sr. Web Developer passionate about blogging and teaching. When I am not coding or writing blogs, I prefer traveling (Which I like most). I am also doing a bit or research on Indian Startups now a days.

Leave a Reply

Your email address will not be published. Required fields are marked *