返回介绍

wp_upload_dir()

发布于 2017-09-11 13:09:46 字数 9937 浏览 1261 评论 0 收藏 0

wp_upload_dir( string $time = null,  bool $create_dir = true,  bool $refresh_cache = false )

Get an array containing the current upload directory’s path and url.


description

Checks the ‘upload_path’ option, which should be from the web root folder, and if it isn’t empty it will be used. If it is empty, then the path will be ‘WP_CONTENT_DIR/uploads’. If the ‘UPLOADS’ constant is defined, then it will override the ‘upload_path’ option and ‘WP_CONTENT_DIR/uploads’ path.

The upload URL path is set either by the ‘upload_url_path’ option or by using the ‘WP_CONTENT_URL’ constant and appending ‘/uploads’ to the path.

If the ‘uploads_use_yearmonth_folders’ is set to true (checkbox if checked in the administration settings panel), then the time will be used. The format will be year first and then month.

If the path couldn’t be created, then an error will be returned with the key ‘error’ containing the error message. The error suggests that the parent directory is not writable by the server.

On success, the returned array will have many indices: ‘path’ – base directory and sub directory or full path to upload directory. ‘url’ – base url and sub directory or absolute URL to upload directory. ‘subdir’ – sub directory if uploads use year/month folders option is on. ‘basedir’ – path without subdir. ‘baseurl’ – URL path without subdir. ‘error’ – false or error message.


参数

$time

(string) (Optional) Time formatted in 'yyyy/mm'.

Default value: null

$create_dir

(bool) (Optional) Whether to check and create the uploads directory. Default true for backward compatibility.

Default value: true

$refresh_cache

(bool) (Optional) Whether to refresh the cache.

Default value: false


返回值

(array) See above for description.


源代码

File: wp-includes/functions.php

function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
	static $cache = array(), $tested_paths = array();

	$key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );

	if ( $refresh_cache || empty( $cache[ $key ] ) ) {
		$cache[ $key ] = _wp_upload_dir( $time );
	}

	/**
	 * Filters the uploads directory data.
	 *
	 * @since 2.0.0
	 *
	 * @param array $uploads Array of upload directory data with keys of 'path',
	 *                       'url', 'subdir, 'basedir', and 'error'.
	 */
	$uploads = apply_filters( 'upload_dir', $cache[ $key ] );

	if ( $create_dir ) {
		$path = $uploads['path'];

		if ( array_key_exists( $path, $tested_paths ) ) {
			$uploads['error'] = $tested_paths[ $path ];
		} else {
			if ( ! wp_mkdir_p( $path ) ) {
				if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
					$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
				} else {
					$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
				}

				$uploads['error'] = sprintf(
					/* translators: %s: directory path */
					__( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
					esc_html( $error_path )
				);
			}

			$tested_paths[ $path ] = $uploads['error'];
		}
	}

	return $uploads;
}

更新日志

Versiondescription
2.0.0Introduced.

More Information

Note that using this function will create a subfolder in your Uploads folder corresponding to the queried month (or current month, if no $time argument is provided), if that folder is not already there. You don’t have to upload anything in order for this folder to be created.

For creating custom folder for users


global $current_user;
get_currentuserinfo();

$upload_dir = wp_upload_dir();
$user_dirname = $upload_dir['basedir'].'/'.$current_user->user_login;
if ( ! file_exists( $user_dirname ) ) {
	wp_mkdir_p( $user_dirname );
}

Folder Name

In case you want to move the /uploads folder, you’ll have to use the UPLOADS constant. It normally shouldn’t get used, as it only get’s defined when ms_default_constants() is run (only multisite), but you can simply set:


define( 'UPLOADS', trailingslashit( WP_CONTENT_DIR ) . 'custom_uploads_name' );

in a single site install and it will just work, as the public directory structure function wp_upload_dir() sets it up, when it was defined:


$dir = ABSPATH . UPLOADS;

Note: You can extract the folder name with the following line:


// returns `false` if the UPLOADS constant is not defined
$upload_dir_name = false;
if ( defined( 'UPLOADS' ) ) {
	str_replace( trailingslashit( WP_CONTENT_DIR ), '', untrailingslashit( UPLOADS ) );
}

相关函数

Uses

  • wp-includes/functions.php: _wp_upload_dir()
  • wp-includes/l10n.php: __()
  • wp-includes/formatting.php: esc_html()
  • wp-includes/load.php: get_current_blog_id()
  • wp-includes/functions.php: wp_mkdir_p()
  • wp-includes/functions.php: upload_dir
  • wp-includes/plugin.php: apply_filters()
  • Show 2 more uses Hide more uses

Used By

  • wp-includes/functions.php: wp_get_upload_dir()
  • wp-admin/includes/file.php: _wp_handle_upload()
  • wp-admin/includes/class-file-upload-upgrader.php: File_Upload_Upgrader::__construct()
  • wp-admin/includes/template.php: wp_import_upload_form()
  • wp-includes/functions.php: wp_upload_bits()
  • wp-includes/ms-functions.php: get_space_used()
  • Show 1 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 4You must log in to vote on the helpfulness of this note Contributed by Codex

    More in-depth break down of the data returned.

    
    <?php
    $upload_dir = wp_upload_dir(); // Array of key => value pairs
    /*
        $upload_dir now contains something like the following (if successful)
        Array (
            [path] => C:\path\to\wordpress\wp-content\uploads\2010\05
            [url] => http://example.com/wp-content/uploads/2010/05
            [subdir] => /2010/05
            [basedir] => C:\path\to\wordpress\wp-content\uploads
            [baseurl] => http://example.com/wp-content/uploads
            [error] =>
        )
        // descriptions
        [path] - base directory and sub directory or full path to upload directory.
        [url] - base url and sub directory or absolute URL to upload directory.
        [subdir] - sub directory if uploads use year/month folders option is on.
        [basedir] - path without subdir.
        [baseurl] - URL path without subdir.
        [error] - set to false.
    */
    
    echo $upload_dir['path'] . '<br />';
    echo $upload_dir['url'] . '<br />';
    echo $upload_dir['subdir'] . '<br />';
    echo $upload_dir['basedir'] . '<br />';
    echo $upload_dir['baseurl'] . '<br />';
    echo $upload_dir['error'] . '<br />';
    
    $upload_url = ( $upload_dir['url'] );
    $upload_url_alt = ( $upload_dir['baseurl'] . $upload_dir['subdir'] );
    
    // Now echo the final result
    echo $upload_url . '<br />'; // Output - http://example.com/wp-content/uploads/2010/05
    
    // Using year and month based folders, the below will be the same as the line above.
    echo $upload_url_alt . '<br />'; // Output - http://example.com/wp-content/uploads/2010/05
    ?>
    
    
  2. Note that the ‘upload_path’ option that is mentioned has been removed since WP3.5, so this check is only still there for backwards compatibility.

    I needed to NOT rely on Gravatar at all, and just use the buddypress profile avatar. Here is the result.

    
    $avatar_url = bp_core_fetch_avatar(array('item_id'=>$user->ID,'html'=>false));        
    if (strpos($avatar_url, 'www.gravatar.com/avatar') !== false) {
    	$upload_dir = wp_upload_dir();
        $avatar_url = $upload_dir['baseurl'] . '/avatars/pi-gravatar.jpg';
    }
    

    Basic example to produce the upload directory URL.

    
    <?php $upload_dir = wp_upload_dir(); ?>
    <?php echo $upload_dir['baseurl']; ?>
    
    
    
    

    If you want to create a directory in wp-contents/uploads folder at the time of WordPress PlugIn activation, here is the code:

    
    function yourprojectname_activate() {
     
        $upload = wp_upload_dir();
        $upload_dir = $upload['basedir'];
        $upload_dir = $upload_dir . '/your-project-name';
        if (! is_dir($upload_dir)) {
           mkdir( $upload_dir, 0700 );
        }
    }
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文