Using data from database in theme

when using another MySql database, you can connect to it with another instance of wpdb. As mentioned on this answer and on the documentation. After retrieving the data from the database it just a matter of doing good ol’ PHP loop.

For example you could have something like this in your functions.php (or in a custom plugin).

function get_data_from_custom_db_with_wpdb( $maybe_accept_pagination_parameter ) {
    $mydb = new wpdb('username','password','database','localhost');
    return $mydb->get_results("select Name from my_table");

Then you’d use it a template like so. Below I’ve used a custom page template as an example, but nothing stops you from using the same code in some other template file (along or replacing the default WP loop).

/* Template Name: My Page Template */

// pagination maybe?
$entries = get_data_from_custom_db_with_wpdb( absint( $_GET['page_num'] ?? 0 ) );

foreach ($entries as $entry) : ?>
    <div class="my-class">
        <?php echo esc_html( $entry->some_property ); ?>
<?php endforeach;


And if you want to separate the entry html into its own file, e.g. /your-theme/parts/entry-news.php, you can easily include it inside the loop with get_template_part().

foreach ($entries as $entry) {
            'something' => $entry->some_property

Starting WP 5.5 the function accepts $args as the third parameter, which you can use to pass data to the partial file. You’d access the data in the template file with $args['something'].

If you need pagination, you’ll probably need to figure that one out yourself as I don’t believe WP’s native pagination plays nicely with custom queries to separate databases.

Be the first to comment

Leave a Reply

Your email address will not be published.