Error getting correct blog_id on MU from functions.php

I have script in my functions.php that seeks to locate the media directory of the site in which the theme is installed. This is pretty simple unless the site is an MU site. In that case, the media directory is based on the blog_id.

However, my code below is returning the main site id rather than the blog_id of the site in which its being run…

Read More
function get_image_list()
{
    global $current_site;
    $dir=is_multisite() ?  'wp-content/blogs.dir/'.$current_site->blog_id.'/files/' : 'wp-content/uploads/';
    $url=is_multisite() ?  get_bloginfo('url').'/wp-content/blogs.dir/'.$current_site->blog_id.'/files/' : get_bloginfo('url').'/wp-content/uploads/';

In this case, the actual blog_id is 3, however, its returning a value of 1 for $current_site->blog_id

The error is…

cannot open wp-content/blogs.dir/1/files/

Related posts

Leave a Reply

2 comments

  1. Compare $current_site->id with $current_site->blog_id. According to the in-line documentation, blog_id should be working … but check to see if there’s a major difference there (your system might have a plug-in or something else causing a problem).


    Update – Ignore last

    It seems like $current_site is a global variable defined by your site or network and will always return the same blog_id as your network dashboard – in this case, “1.”

    What you need to use instead is $current_blog:

    function get_image_list() {
        global $current_blog;
        $dir=is_multisite() ?  'wp-content/blogs.dir/'.$current_blog->blog_id.'/files/' : 'wp-content/uploads/';
        $url=is_multisite() ?  get_bloginfo('url').'/wp-content/blogs.dir/'.$current_blog->blog_id.'/files/' : get_bloginfo('url').'/wp-content/uploads/';
    

    That should get you the right information.

  2. Another gotcha is your hard coded /wp-content/.
    Use WP_CONTENT_DIR for file access and WP_CONTENT_URL for HTTP requests or better yet wp_upload_dir() for both. I have some installations running where wp-content is on another domain and in a path outside of the WordPress directory.

    So, even if you get the correct blogi_id, you may not find the files. 🙂

    Update

    My little debug plugin Show Upload Info may give some hints. But the results of is_dir() aren’t reliable, unfortunately.