The essence of the question is, I’m looking for a solution like this:

$blog_upload_dir_info = wp_upload_dir( $date, $blog_ID );
$blog_upload_url = $blog_upload_dir_info[ 'baseurl' ];

Where $blog_ID is different of the current blog ID. The most »WP-obvious« solution fails:

switch_to_blog( $blog_ID );
$blog_upload_dir_info = wp_upload_dir();
restore_current_blog();

as wp_upload_dir() relies on the constant WP_CONTENT_URL which is dynamically set the URL of the current blog unless the option upload_url_path is set.

Of course, I could set this option, but this would couple my code to concrete system settings which includes much »WTF?«-potential.

So I decided to add this option virtually:

/**
 * Apply a value to the option blog_upload_url 
 * if there's not already one 
 *
 * @wp-hook option_upload_url_path
 * @param string $upload_url
 * @return string
 */
function get_real_blog_upload_url( $upload_url ) {

    if ( '' !== trim( $upload_url ) )
        return $upload_url;

    $upload_path = trim( get_option( 'upload_path' ) );
    $siteurl = get_option( 'siteurl' );
    $wp_content_dir = $siteurl . '/wp-content';

    if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
        $dir = $wp_content_dir . '/uploads';
    } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
        // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
        $dir = path_join( ABSPATH, $upload_path );
    } else {
        $dir = $upload_path;
    }

    if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
        $upload_path = $wp_content_dir . '/uploads';
    else
        $upload_path = trailingslashit( $siteurl ) . $upload_path;


    return $upload_path;
}

which is in fact a partly fork of wp_upload_dir() and as such relies on constants which isn’t a good practice at all. Moreover a fork is always coupled to the original implementation and if the original changes, one also have to fix the fork.

So as this solution is far away from being perfect, I wonder if there’s a better way to get upload URLs by blog IDs.

2 s
2

Why not just use get_option('upload_path') after your switch_to_blog( $blog_ID );?
Does that do it?

Leave a Reply

Your email address will not be published. Required fields are marked *