Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the polylang domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/vajnabot/public_html/wp-includes/functions.php on line 6121
Vajna Botond | Online portofolio | Access data from another WordPress database

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.