Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

wordpress - Using WPDB in standalone script?

I am trying to connect to WordPress using the WPDB because it's such a beautiful class and also there are configurations that specified in wp-config.php so i won't need to specify it again.

I going to write a small separated script from main WordPress to run in background that will need to use this WPDB instance.

How can I archive this?

Any help is appreciated.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best(fastest and safest) way to load only load the core functionality of WordPress is to use the SHORTINIT flag like this:

define( 'SHORTINIT', true );

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

//Here you can use WordPress core features, for example the $WPDB object

For more information about this and see what is loaded, is to check the code in /wp-settings.php. There you will find the following section:

// Stop most of WordPress from being loaded if we just want the basics.
if ( SHORTINIT )
    return false;

This means that anything after this won't be loaded, and it's quite a lot of things as you can see. The footprint will be much smaller than just loading the wp-load.php and still gives you access to all the all the built in functions in WordPress core, unlike including for example /wp-includes/wp-db.php directly. Many functions in WP core also has dependencies in other files and it can be a mess to figure out exactly what files you need to include to be able do what you want. SHORTINIT includes the needed dependencies so you don't have to worry about this.

If you know exactly what you need, for example only WPDB, the fastest way is of course to only include the files you need, but SHORTINIT provides a safer and more standardised way to load the WP core and the dependencies. With SHORTINIT WordPress does not load plugins, most parts of the plugin API, themes, theme functions and most admin and frontend functions. This is where the heavy code is in a typical WordPress install. In most cases I think SHORTINIT is worth the small tradeoff in speed/performance compared to including only the files you need and it's in most cases a huge performance boost compared to a full load.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...