WordPress Custom Database Tables: A Guide

Leveraging Existing Databases with WordPress
WordPress is renowned for its adaptability as a Content Management System (CMS). Exploring resources like the Best of WordPress Plugins page demonstrates the platform’s extensive capabilities and specialized functionalities.
Previously, methods for enhancing WordPress functionality, including the implementation of custom post types for creating bespoke databases, have been discussed.
Connecting to External Data Sources
However, a common scenario involves utilizing pre-existing databases, such as those containing customer information. The need arises to access and present this data seamlessly within a WordPress template.
This guide will detail a secure method for querying external databases and displaying the retrieved information directly within the WordPress environment.
Safely Integrating Database Queries
The core challenge lies in establishing a connection to an external database without compromising the security of the WordPress installation.
Directly embedding database credentials within theme files is strongly discouraged due to potential vulnerabilities. A more robust approach involves utilizing a dedicated plugin or creating a custom function to manage the database connection.
Key Considerations
- Security: Protect database credentials diligently.
- Performance: Optimize queries to minimize server load.
- Maintainability: Ensure the integration is easily updated and maintained.
By following these guidelines, you can effectively extend the functionality of your WordPress site by harnessing the power of existing data sources.
This allows for dynamic content generation and personalized experiences, all while maintaining a secure and efficient website.
Prerequisites
A self-hosted WordPress site is essential, naturally.
Fundamental knowledge of PHP and MySQL is required – the Tizag tutorials for both are highly recommended. They provide comprehensive coverage and can be completed within a day, serving as a valuable reference point.
You will need an existing dataset already stored in MySQL.
Access to the PHPMyAdmin command line is necessary for database merging.
A unified database containing both datasets is the ultimate goal. This involves either integrating your WordPress database tables into a pre-existing database and updating the wp-config.php file with the new database credentials, or importing an existing dataset directly into your WordPress database.
Database Considerations
- It’s simpler to proceed if no other systems depend on the data you are manipulating.
- For those needing guidance on database backups, a previous article details how to perform a full backup via the SSH command line.
This guide represents the most technically demanding content typically featured on MakeUseOf, but it unlocks a wide range of potential applications.
Successfully completing these steps will empower you with greater control and flexibility over your WordPress installation.
Leveraging Existing Data in WordPress
While WordPress offers numerous plugins and extensions, importing pre-existing datasets can sometimes prove more complex than anticipated. This is particularly true when interoperability with other systems is also required.
This guide demonstrates how to display data from a custom database within WordPress, specifically focusing on a customer information database. Access to this information will be restricted to registered users, though the page itself will be publicly accessible.
For clarity regarding database structure, including column and table names, the Database Browser plugin is a valuable resource. It also facilitates basic SQL queries, allowing you to test your code effectively.
Database Exploration
Consider installing the Database Browser plugin to gain insight into your database schema. This tool enables you to execute where and order by clauses for testing SQL queries.
As an example, a table named 'Customers' has been created, containing essential details about valued clients. The following screenshot illustrates a sample dataset.

Defining the Scope of Our Task
The primary objective is the development of a novel page template. This template will serve as a foundation for incorporating bespoke PHP scripting.
We will also explore the process of constructing a tailored database query within the WordPress environment. This includes retrieving data and interpreting the results using WordPress’s integrated database functionalities.
Key Areas of Investigation
- Establishing a new page template for future customization.
- Developing a custom database query and parsing its output using native WordPress database classes.
- Implementing permission controls to potentially limit access to the template’s functionality.
Template Creation and PHP Integration
A new page template provides a dedicated space for implementing custom PHP code. This separation ensures that core WordPress functionality remains unaffected by the added scripting.
The template will be designed to accommodate specific requirements, allowing for dynamic content generation and tailored user experiences.
Custom Database Queries in WordPress
WordPress offers robust tools for interacting with the database. We will focus on crafting a specific query to extract desired information.
The results obtained from the query will then be processed and displayed using WordPress’s built-in database classes, ensuring compatibility and efficiency.
Utilizing WordPress Database Classes
- These classes simplify database interactions.
- They provide a secure and standardized method for querying and retrieving data.
- Using these classes promotes code maintainability and reduces the risk of errors.
Implementing Access Permissions
Controlling access to the template’s functionality is crucial for security and user management. Permission checks can be integrated to restrict access based on user roles or capabilities.
This ensures that sensitive information or administrative features are only accessible to authorized personnel.
Permissions are essential for maintaining a secure and controlled WordPress environment.
Creating a Personalized Template
To integrate your own PHP code, a streamlined approach involves crafting a custom template and then assigning it to a specific page within your Wordpress installation. Begin by accessing your theme files and replicating the page.php file (or single.php if page.php is unavailable). Give the duplicated file a descriptive name, such as "template-customers.php," as an example.
At the beginning of this new file, it’s essential to inform Wordpress that this is a custom template. Accomplish this by inserting the following code (this is a PHP comment, so ensure it follows any existing opening PHP tag):
/*Template Name: Customers
*/
Naturally, you can choose any suitable name for your template.
Next, locate the primary content function within the file. You have the option to delete the existing function, or alternatively, append your additional code after it. In the default twenty-eleven theme, look for:
<?php get_template_part( 'content', 'page' ); ?>
However, many themes utilize a structure similar to this:
<?php the_content();?>
This section is responsible for displaying the content of your post. Any code added following this will appear immediately after the main content area. To verify functionality, let's add a simple echo statement and save the file.
<?php echo "This is our custom template!";?>
Prior to testing, you must create a new page within the Wordpress administration panel and apply your newly created page template to it.

Publish the page and then view it in your browser to confirm that the echo statement is displayed correctly.

Utilizing the Custom Query Class
Direct database access within WordPress is achievable by leveraging the global $wpdb object. Implementing the following three lines of code will facilitate this, effectively replacing the previous echo statement:
get_results("SELECT * FROM customers;");
print_r($customers);
?>Upon saving these changes and refreshing the page, the print_r() function will output all data retrieved from the customers object. This confirms the successful execution of the SQL statement designed to select all entries from the customer table. The next step involves processing these results into a usable format.
While the get_results() method accommodates any valid SQL select statement, this discussion will focus on retrieving all data for simplicity. To transform the results into a more organized presentation, a basic table will be employed. Substitute the print_r function with the following code snippet (a complete code listing will be provided later for convenience):
echo "<table>";
foreach($customers as $customer){
echo "<tr>";
echo "<td>".$customer->name."</td>";
echo "<td>".$customer->email."</td>";
echo "<td>".$customer->phone."</td>";
echo "<td>".$customer->address."</td>";
echo "</tr>";
}
echo "</table>";Within a foreach loop, each customer object's fields can be accessed using the $customer->field_name syntax. This method provides a straightforward and intuitive way to retrieve specific data points.
Data Security Measures
Protecting sensitive customer information from unauthorized access and search engine indexing is crucial. However, displaying this data on the front end using a template is often necessary. A solution involves leveraging the WordPress conditional function is_user_logged_in() to control visibility.
This conditional allows for a simple message to be shown to users who are not logged in, effectively hiding the data from them. The complete code block, incorporating this conditional, is presented below:
get_results("SELECT * FROM customers;"); echo "<table>"; foreach($customers as $customer){ echo "<tr>"; echo "<td>".$customer->name."</td>"; echo "<td>".$customer->email."</td>"; echo "<td>".$customer->phone."</td>"; echo "<td>".$customer->address."</td>"; echo "</tr>"; } echo "</table>"; else: echo "Sorry, only registered users can view this information"; endif; ?>
After saving the changes and refreshing the page, the content should remain visible to logged-in users. Logging out and then refreshing will reveal the "Sorry, only registered users…" message, confirming the restriction.

For more granular control, restricting access to specific user roles is possible. Instead of is_user_logged_in(), the current_user_can() conditional can be utilized. This requires specifying a corresponding capability.
The WordPress codex provides detailed information regarding user capabilities. For instance, to limit access to administrators who manage plugin options, the following code snippet can be used:
current_user_can( 'manage_options' )
Concluding Remarks
I will conclude my discussion here, as further elaboration could easily transition into a detailed SQL tutorial or a guide on output styling with CSS. The possibilities within WordPress are truly extensive, and it is my hope that this information proves beneficial to those engaged in WordPress development.
My next article will address the more complex subject of integrating data from a webpage form into a custom database, utilizing AJAX and jQuery techniques. Furthermore, I encourage you to explore our other WordPress resources, such as guides for resolving 500 internal server errors and addressing blank page issues, as well as information on featured thumbnail and image dimensions.
If you haven't yet established a WordPress environment, our guide to installing WordPress on Bluehost may be a helpful starting point.