WordPress.org

Make WordPress Core

Opened 4 months ago

Last modified 2 months ago

#43119 new defect (bug)

Allow passing empty post ID to media_handle_sideload()

Reported by: swissspidy Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 2.6
Component: Media Keywords: has-unit-tests has-patch
Focuses: Cc:

Description

I stumbled upon this via https://wordpress.stackexchange.com/questions/291344/why-does-media-handle-sideload-upload-to-last-months-folder.

Basically, the person was trying to run media_handle_sideload( $file_array, $post_id = 0 ) to upload files. This works fine in so far as it calls wp_insert_attachment() which accepts a post ID of 0 (it's the default) so the attachment won't be associated with a specific post.

However, media_handle_sideload() doesn't fully support $post_id = 0 (or $post_id = null, for that matter) because of the if ( $post = get_post( $post_id ) ) { … } condition since get_post( 0 ) fetches the global post and overrides $time.

This means you cannot upload a media file and have $time set to today.

To reproduce:

  1. Create a post with the date set to last month
  2. Set this post as $GLOBALS['post']
  3. Run media_handle_sideload( $file_array, 0 )
  4. Notice that the upload folder will be the one from last month, not this month.

Proposed fix:

Change the condition from if ( $post = get_post( $post_id ) ) { … } to if ( $post_id && $post = get_post( $post_id ) ) { … }

Consequences:

The upload folder will point to the current month, not the date from the global post if using $post_id = 0 or $post_id = null. Not a big deal IMHO.

Attachments (3)

43119.diff (424 bytes) - added by AugusGils 3 months ago.
Made a check on $post_id to make sure it's a valid one, this to make sure the correct upload folder is used.
43119-unit-tests.diff (1.8 KB) - added by andizer 2 months ago.
Added unit tests for covering the touched lines.
43119.2.diff (3.5 KB) - added by birgire 2 months ago.

Download all attachments as: .zip

Change History (5)

@AugusGils
3 months ago

Made a check on $post_id to make sure it's a valid one, this to make sure the correct upload folder is used.

@andizer
2 months ago

Added unit tests for covering the touched lines.

#1 @andizer
2 months ago

  • Keywords has-unit-tests added; needs-unit-tests removed

@birgire
2 months ago

#2 @birgire
2 months ago

  • Keywords has-patch added; needs-patch removed

Thanks for patch @AugusGils and the tests @andizer

In 43119.2.diff there are some adjustments:

  • Combines patch + tests into a single patch.
  • To speed things up it avoids the download_url() and uses an existing file instead.
  • Changes $default = date( '/Y/m', current_time( 'timestamp' ) ); to $default = current_time( '/Y/m/' ); for simplification.
  • Some changes according to the Coding Standard.
  • Adds cleanups.

Hope it helps.

Note: See TracTickets for help on using tickets.