WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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; ?>
share|improve this question
up vote 1 down vote accepted

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 
share|improve this answer
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;  
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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