Vajna Botond

Designer

Access data from another WordPress database

To retrieve data from a different database within WordPress, you must create a custom query utilizing the $wpdb class. This class facilitates interaction with multiple databases in the WordPress environment.

Below is an illustration of how you can retrieve information from the wp_posts and wp_postmeta tables in another database:

global $wpdb;

// Define the database credentials for the other database
$other_db_name = 'other_database_name';
$other_db_user = 'other_database_user';
$other_db_password = 'other_database_password';
$other_db_host = 'other_database_host';

// Connect to the other database
$other_db = new wpdb($other_db_user, $other_db_password, $other_db_name, $other_db_host);

// Define the tables to access
$posts_table = $other_db->prefix . 'posts';
$postmeta_table = $other_db->prefix . 'postmeta';

// Query the data
$posts = $other_db->get_results("SELECT * FROM $posts_table");
$postmeta = $other_db->get_results("SELECT * FROM $postmeta_table");

Subsequently, you can utilize the $posts and $postmeta variables to access the data from the secondary database. The remaining data from your current WordPress website’s database can be accessed using the default $wpdb object, eliminating the need to establish a connection to an additional database.