I am trying to add the most recent post from another Wordpress database (on the same server in all actuality), but am getting the following error:

Fatal error: Call to undefined method wpdb::query_posts() in /var/www/site/wp-content/themes/custom/footer.php on line 68

Here is the code:

<!-- .entry-content -->
$originaldb = new wpdb('username', 'password', 'db', 'localhost');
$originaldb->query_posts( 'posts_per_page=1' );  
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 

<header class="entry-header">
        <div class="entry-meta">
            <?php echo '<span class="entry-day">'.get_the_date('j').'</span><br><span class="entry-month">'.get_the_date('M').'</span>'; ?>
        <div class="title-box">
            <h2 class="blog-title"><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h2>
            <?php echo '<a href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">' . the_author() . '</a>'; ?>
        <div class="clear"></div>
    <div class="entry-content">
        <?php the_excerpt(); ?>

<?php endwhile; else: ?>  
Testing has failed
<?php endif; ?>

2 Answers 2


The Wordpress wpdb class is a little different than the normal way of querying in that you run "vanilla" database queries.

You can see documentation on the wpdb class on the Wordpress docs: http://codex.wordpress.org/Class_Reference/wpdb#Run_Any_Query_on_the_Database

Also, in regard to your code, you should be able to change the line here:

$originaldb->query_posts( 'posts_per_page=1' );

To something like this:

$results = $originaldb->get_results( "SELECT * FROM $wpdb->posts LIMIT 1" );

This will provide you with an array of posts that you can then process with a loop:

  foreach($results as $post): setup_postdata($post); 
    // do stuff with normal wp template tags
  // no posts 
function get_other_posts() {
    $wpdb_old = wp_clone( $GLOBALS['wpdb'] );
    $wpdb_new = &$GLOBALS['wpdb'];  

    // All you have to care about following two lines
    $wpdb_new = new wpdb( 'your_db_username', 'db_password', 'new_db_name', 'localhost' );
    $wpdb_new->set_prefix( 'wp_' );

    // Now whatever function you'll call, it will use new database
    $posts = get_posts( 'numberposts=5' );

    // We are done so lets take the old wpdb back on its position
    $wpdb_new = $wpdb_old;  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.