How can you upload an image from within a settings page?

Is there an easy way to include an upload box to your settings page?

I am building an Open Graph options page and I like users to upload a standard image directly from that page.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

WordPress provides a convenient function for just this purpose: wp_handle_upload().

Assuming that you already have the appropriate file form field in your settings page, and that you’re using register_setting() for your options, and therefore already have an options validation callback, simply handle the file form field data using wp_handle_upload(). Here’s an example:

<?php
// Validate file fields
else if ( 'file' == $optiondetails['type'] ) {
    if ( isset( $input[$setting] ) ) {
        // Only update setting if input value is in the list of valid options
        $setting_file = $setting . '_file';
        $valid_input[$setting] = ( isset( $_FILES[$setting_file] ) ? theme-slug_image_upload( $setting, $input ) : $valid_input[$setting] );
    }
}
?>

Then, you just need to define that theme-slug_image_upload() callback, using wp_handle_upload():

<?php
function theme-slug_image_upload( $the_file, $input ) {
    $data = $_FILES[$the_file . '_file'];
    if ( '' != $data['name'] )
        $upload = wp_handle_upload( $_FILES[$the_file . '_file'], array( 'test_form' => false ) );
    else
        $upload['url'] = $input[$the_file];
    return $upload['url'];
}
?>

That’s pretty much it.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x