WordPress.org

Ready to get started?Download WordPress

Forums

Get the correct table prefix (8 posts)

  1. modifiedcontent
    Member
    Posted 2 years ago #

    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?

  2. s_ha_dum
    Member
    Posted 2 years ago #

    global $wpdb; // you may not need this part. Try with and without it
    echo $wpdb->prefix; // here is your database prefix
  3. modifiedcontent
    Member
    Posted 2 years ago #

    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?

  4. s_ha_dum
    Member
    Posted 2 years ago #

    $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.

    http://codex.wordpress.org/Class_Reference/wpdb#Tables

  5. modifiedcontent
    Member
    Posted 2 years ago #

    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.

  6. s_ha_dum
    Member
    Posted 2 years ago #

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

    Sort of interesting that multisite can't cope more gracefully...

  7. modifiedcontent
    Member
    Posted 2 years ago #

    Thanks!

    > 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.

    Edit:

    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.

  8. modifiedcontent
    Member
    Posted 2 years ago #

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

    $wpdb->base_prefix

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags