WordPress April 23, 2026 12 min read

How to Connect WordPress to an External Database

WordPress stores its data in a MySQL database — posts, pages, users, settings. But what if your business data lives somewhere else? Maybe you have a CRM running on a separate MySQL server, inventory in PostgreSQL, or a custom application with its own database. How do you get that data into WordPress?

This guide covers three methods to connect WordPress to external databases, from code-heavy solutions to no-code plugins. We'll walk through the pros and cons of each approach so you can pick the right one for your situation.

What You'll Learn

  • Method 1: Custom PHP code with wpdb or PDO
  • Method 2: Using a reporting plugin (no code required)
  • Method 3: REST API integration
  • Security best practices for external connections

Why Connect to an External Database?

Common use cases we see:

  • Business reporting — Display sales data, inventory levels, or customer metrics on your WordPress dashboard
  • Data portals — Let customers or partners view their own data through your WordPress site
  • Legacy system integration — Connect to existing databases without migrating data
  • Multi-system dashboards — Combine data from CRM, ERP, and other systems in one place

The key challenge: WordPress doesn't natively support connecting to external databases. The built-in $wpdb object only connects to your WordPress database. You need another approach.

Method 1: Custom PHP Code

The developer approach. You write PHP code to establish a connection, run queries, and display results. This gives you complete control but requires coding knowledge and ongoing maintenance.

Using PDO (Recommended)

PDO (PHP Data Objects) is the modern way to connect to databases in PHP. It supports MySQL, PostgreSQL, SQLite, and more with a consistent API.

<?php
// Add this to your theme's functions.php or a custom plugin

function get_external_db_connection() {
    static $pdo = null;

    if ($pdo === null) {
        try {
            $pdo = new PDO(
                'mysql:host=your-server.com;dbname=your_database;charset=utf8mb4',
                'username',
                'password',
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]
            );
        } catch (PDOException $e) {
            error_log('External DB connection failed: ' . $e->getMessage());
            return null;
        }
    }

    return $pdo;
}

// Example: Fetch data from external database
function get_external_customers() {
    $pdo = get_external_db_connection();
    if (!$pdo) return [];

    $stmt = $pdo->query('SELECT * FROM customers ORDER BY created_at DESC LIMIT 100');
    return $stmt->fetchAll();
}

For PostgreSQL

Change the DSN (first parameter) to use the PostgreSQL driver:

'pgsql:host=your-server.com;dbname=your_database'

Displaying Data with a Shortcode

Create a shortcode to display external data anywhere on your site:

function external_customers_shortcode() {
    $customers = get_external_customers();

    if (empty($customers)) {
        return '<p>No customers found.</p>';
    }

    $html = '<table class="wp-block-table"><thead><tr>';
    $html .= '<th>Name</th><th>Email</th><th>Joined</th>';
    $html .= '</tr></thead><tbody>';

    foreach ($customers as $customer) {
        $html .= sprintf(
            '<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
            esc_html($customer['name']),
            esc_html($customer['email']),
            esc_html($customer['created_at'])
        );
    }

    $html .= '</tbody></table>';
    return $html;
}
add_shortcode('external_customers', 'external_customers_shortcode');

Then use [external_customers] in any post or page.

Pros and Cons of Custom Code

Pros

  • Complete control over queries
  • No plugin dependencies
  • Can be optimized for your exact needs

Cons

  • Requires PHP knowledge
  • You handle all security yourself
  • No visual interface for building queries
  • Maintenance burden over time

Method 2: Use a Reporting Plugin (No Code)

If you want external database connections without writing code, a WordPress reporting plugin is the way to go. The best ones provide:

  • Visual query builder (no SQL required)
  • Multiple database type support (MySQL, PostgreSQL)
  • Charts and visualizations
  • Dashboard builder
  • Shortcode embedding
  • Built-in security (encrypted credentials, read-only queries)

EverNext Reporting is designed exactly for this. Connect to MySQL, MariaDB, or PostgreSQL databases, build queries visually or with SQL, and embed reports anywhere on your site with shortcodes.

Step-by-Step: Connect External Database with EverNext Reporting

  1. Install and activate the plugin from WordPress admin
  2. Go to EverNext Reporting → Connections
  3. Click Add New Connection
  4. Enter your database credentials (host, port, database name, username, password)
  5. Click Test Connection to verify
  6. Save the connection

That's it. Your external database is now connected. Create a new report, select your connection, and start building queries with the visual builder or SQL editor.

Pros and Cons of Plugin Approach

Pros

  • No coding required
  • Visual query builder
  • Built-in security (encryption, SQL injection prevention)
  • Charts, dashboards, scheduling included
  • Non-technical team members can build reports

Cons

  • Plugin dependency
  • May have licensing costs for pro features

Method 3: REST API Integration

If your external system has a REST API, you can fetch data without a direct database connection. This is common when integrating with SaaS platforms, third-party services, or microservices.

function fetch_external_api_data() {
    $response = wp_remote_get('https://api.example.com/customers', [
        'headers' => [
            'Authorization' => 'Bearer YOUR_API_KEY',
        ],
        'timeout' => 30,
    ]);

    if (is_wp_error($response)) {
        return [];
    }

    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}

This works well when you don't have direct database access, but it requires the external system to expose an API.

Security Best Practices

Connecting to external databases introduces security considerations. Follow these practices regardless of which method you use:

1. Use a Read-Only Database User

Create a dedicated database user with SELECT permissions only. Never use root or admin credentials.

CREATE USER 'wordpress_reader'@'%' IDENTIFIED BY 'secure_password';
GRANT SELECT ON your_database.* TO 'wordpress_reader'@'%';

2. Use SSL/TLS Connections

Encrypt data in transit, especially when connecting over the internet. Most cloud databases (AWS RDS, Google Cloud SQL, etc.) support SSL by default.

3. Whitelist IP Addresses

Configure your database firewall to only accept connections from your WordPress server's IP address.

4. Never Expose Credentials in Code

Store credentials in wp-config.php or environment variables, not in theme files or plugins that might end up in version control.

// In wp-config.php
define('EXTERNAL_DB_HOST', 'your-server.com');
define('EXTERNAL_DB_NAME', 'your_database');
define('EXTERNAL_DB_USER', 'wordpress_reader');
define('EXTERNAL_DB_PASS', 'secure_password');

5. Use Prepared Statements

Always use parameterized queries to prevent SQL injection. Never concatenate user input directly into SQL strings.

// WRONG - vulnerable to SQL injection
$pdo->query("SELECT * FROM users WHERE id = $user_id");

// CORRECT - safe with prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);

Which Method Should You Choose?

  • Choose custom PHP code if you're a developer who wants full control and doesn't need visualizations or a UI for non-technical users.
  • Choose a reporting plugin if you want a no-code solution with charts, dashboards, and the ability for your team to build reports without developer help.
  • Choose REST API integration if your external system doesn't allow direct database access but offers an API.

For most businesses, a reporting plugin like EverNext Reporting is the fastest path to value. You get database connectivity, security, and visualizations out of the box — without maintaining custom code.

Conclusion

Connecting WordPress to external databases opens up powerful possibilities: real-time dashboards, customer portals, consolidated reporting across systems. Whether you choose custom code, a plugin, or API integration depends on your technical resources and long-term maintenance capacity.

The key is getting your data where your team can actually use it — and for most WordPress sites, that means bringing external data directly into the admin dashboard or frontend pages where people already work.