Original link: https://www.williamlong.info/archives/6921.html
When using WordPress, sometimes there is such a demand, that is, you want to directly use the database operation classes encapsulated in WordPress to perform read and write queries on the WordPress database. Here is the specific usage method.
Method 1: Use wp-load.php
At the beginning of the php file, add the following statement
define( ‘WP_USE_THEMES’, false );
require_once( $_SERVER[ ‘DOCUMENT_ROOT’ ] . ‘/wp-load.php’ );
After that, you can perform operations such as database read and write queries by operating the $wpdb class. An example is as follows.
<?php $wpdb->query(“DELETE FROM $wpdb->post WHERE post_id = 1”); ?>
<?php $wpdb->get_results(“SELECT ID, post_title FROM $wpdb->posts WHERE post_status = ‘draft’ “); ?>
read a variable
<?php $wpdb->get_var(“SELECT SUM(meta_value) FROM $wpdb->postmeta WHERE meta_key = ‘views'”); ?>
read a line
<?php $wpdb->get_row(“SELECT * FROM $wpdb->links WHERE link_id = 10”); ?>
Method 2: Only use wp-db.php
In method 1, wp-load.php will continue to load a lot of files. In fact, the core file is only wp-db.php. If we only perform database operations and no other operations, then we can only load wp- db.php this file.
The specific method is:
Copy the wp-config.php file to another file, such as wp-config-db.php, edit this file, and delete the line require_once(ABSPATH.’wp-settings.php’) at the end of the file.
Copy wp-db.php from the wp-includes directory to the root directory, edit the wp-db.php file in the root directory, search for filter, and delete the statement containing this word. Search for foreach ( $modes as $i => $mode ) and delete the code snippet for this statement.
After that, at the beginning of the php file, add the following lines.
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
After that, you can use the read query statement in Method 1.
The advantage of this method is that you don’t need to install the WordPress PHP system, you only need two files: wp-config-db.php and wp-db.php to perform database operations, the database operation statements and the statements of the original WordPress system Same.
This article is reprinted from: https://www.williamlong.info/archives/6921.html
This site is for inclusion only, and the copyright belongs to the original author.