Adam Tomat
Adam Tomat

Reputation: 11506

Wordpress Database with custom table

I am trying to pull data from a table I have imported into my wordpress database.

My php code works for all the default wp_ tables but when try and target the tables I actually want I get bugger all back.

My code (currently echoing all post titles and it works)

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->posts
 WHERE post_status = 'publish'") );

 foreach ($liveposts as $livepost) {
  echo '<p>' .$livepost->post_title. '</p>';
}

I imported 3 tables from another database, and yes they do have data in to pull out. I found out that the $wpdb->posts expects the posts table to be wp_posts.. so I tried renaming my tables to wp_bus_route... but still nothing.

I used phpMyAdmin to export 3 tables out of a large database (in a .sql format) and imported them. i can see the tables in phpMyAdmin and view all the data in them.

This is my 1st time pulling data from the wp database so I am missing something obvious.

Upvotes: 0

Views: 6490

Answers (2)

Steve Taylor
Steve Taylor

Reputation: 1951

Referencing the table name like $wpdb->posts only works for standard WP tables. For custom tables, build the table name like this:

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "tablename WHERE post_status = 'publish'") );

Never, never, never hard-code the prefix. This can be changed in wp-config.php, and many people change it to something other than wp_. Changing it from wp_ is a good security measure. Even if it's your own code and your own site, $wpdb->prefix is a best practice that's worth making into a habit.

Upvotes: 7

antyrat
antyrat

Reputation: 27765

Try to not using variables at table names:

$liveposts = $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_bus_route
 WHERE post_status = 'publish'") );

Upvotes: 2

Related Questions