Support » Plugins » Get the correct table prefix

  • I found a useful function, but it has this dodgy bit of code:

    if ($blogs) {
    //we use blog id to loop post query
    foreach ($blogs as $blog) {
    		$blogPostsTable = 'wp_'.$blog.'_posts';
    		$db_query = "SELECT $blogPostsTable.ID,

    The ‘wp_’ obviously causes problems in sites that don’t use the default prefix.

    How can I rewrite this?

Viewing 7 replies - 1 through 7 (of 7 total)
  • global $wpdb; // you may not need this part. Try with and without it
    echo $wpdb->prefix; // here is your database prefix

    Thanks s_ha_dum (was aplijdi)!

    This works in one site, but not in another that has the regular wp_ prefix:

    $blogPostsTable = $wpdb->prefix.''.$blog.'_posts';

    The syntax is probably wrong. What would be the correct way?

    $wpdb->prefix should be the prefix all by itself. You shouldn’t have to build a string like that (unless maybe if you are working with multisite… I’m not familiar with the inner working of that.)

    There are some shortcuts for the WordPress default tables. For wp_posts use $wpdb->posts. For wp_users use, $wpdb->users. And so on.

    Yes, this is for multisite. The $blog variable stands for different blogs on the network, so default wp shortcuts are useless in this case.

    $wpdb->prefix would probably work if I could figure out the right php syntax, the right combination of dots and apostrophes or whatever.

    That is just basic PHP, so if anyone has a clue, please share.

    This $wpdb->prefix.$blog.'_posts' should give you ‘wp_ablogname_posts’

    Sort of interesting that multisite can’t cope more gracefully…


    > Sort of interesting that multisite can’t cope more gracefully…

    MultiSite is designed for blog farms; completely separate blogs side by side. To do anything useful with it, like a community hub for an organization or company, you have to restructure the whole thing.


    The solution still doesn’t work for another site that has the default wp_ prefix. Ugh… Some obscure WP bug again? Will have to keep it hardcoded there.



    $wpdb->prefix turns out to be wrong. To get just ‘wp_’ or whatever you use as prefix, you have to use this:


Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Get the correct table prefix’ is closed to new replies.