2 mins read
Connect Another Database to WordPress and Display Data
- Create the Custom Database:
- First, you need to create the custom database where your table resides. You can do this using a tool like phpMyAdmin or any other database management tool provided by your hosting provider.
- Create a Table (if not already created):
- Within your custom database, create a table where you will store the data you want to access from WordPress. Make sure the table structure matches your requirements.
- Access WordPress Files:
- Access your WordPress installation files using an FTP client or the file manager provided by your hosting provider.
- Edit
wp-config.php:- Locate your WordPress installation’s
wp-config.phpfile. - Before the line that says
/* That's all, stop editing! Happy blogging. */, add the following lines of code to define the new database connection:
- Locate your WordPress installation’s
define('CUSTOM_DB_NAME', 'your_custom_database_name');
define('CUSTOM_DB_USER', 'your_database_username');
define('CUSTOM_DB_PASSWORD', 'your_database_password');
define('CUSTOM_DB_HOST', 'localhost'); // Change this if your database is on a different host
Create a New Connection:
- After defining the constants in
wp-config.php, you need to establish a new database connection wherever you need to interact with the custom database. For example, you might create a new plugin or modify an existing one.
Query Your Custom Table:
- Once you have established the connection, you can use standard SQL queries to interact with your custom table. Here’s an example of how you can retrieve data from a specific table:
- Display the Data:
- After querying your custom table, you can use PHP to display the retrieved data wherever you need it on your WordPress site. This could be within a theme file, a custom page template, or a plugin file.
That’s it! By following these steps, you should be able to connect WordPress to a second custom database and call a specific table within that database. Make sure to replace placeholder values like your_custom_database_name, your_database_username, your_database_password, and your_custom_table with your actual database details.
<div class="row">
<?php
$custom_db = new wpdb('User','Pass','Database','localhost');
// Querying data from the custom table
$results = $custom_db->get_results("SELECT * FROM Table", ARRAY_A);
// Checking if there are any results
if ($results) {
// Looping through the results and displaying them
foreach ($results as $result) {
echo '<div class="col-3" col-sm-12">';
echo 'ID: ' . $result['id'] . '<br>'; // Assuming your table has a column named 'id'
echo 'Name: ' . $result['name'] . '<br>'; // Assuming your table has a column named 'name'
echo 'Color: ' . $result['color'] . '<br>'; // Assuming your table has a column named 'color'
// You can continue echoing other columns as needed
echo '</div><br>';
}
} else {
echo 'No results found.';
};
?>
</div>
