Allow File Uploads To a Post With WordPress 'post_edit_form_tag' Action

Allow File Uploads To A Post With WordPress ‘post_edit_form_tag’ Action

While working on a custom post type, I needed to upload a single photo with a post object. The form element in wp-admin/post-new.php or wp-admin/post.php does not allow file uploads by default. I have seen examples using javascript to append the needed enctype="multipart/form-data" attribute to the form element, but I wanted to avoid javascript.

Within the source code, I found the post_edit_form_tag action within the form element.

<form name="post" action="post.php" method="post" id="post" <?php do_action( 'post_edit_form_tag' ); />

By providing a callback to the post_edit_form_tag action, we can append the needed form attributes to allow files to be sent with the http post form.

add_action( 'post_edit_form_tag', 'custom_edit_form_tag' );
/**
 * Callback for WordPress 'post_edit_form_tag' action.
 * 
 * Append enctype - multipart/form-data and encoding - multipart/form-data
 * to allow image uploads for post type 'post'.
 * 
 * @global WP_Post $post
 */
function custom_edit_form_tag() {

    global $post;

    if ( $post && 'post' === $post->post_type ) {
        printf( ' enctype="multipart/form-data" encoding="multipart/form-data" ' );
    }

}

Now files can be uploaded within the WordPress admin post editor.

Published by

rfmeier

Product developer at WPEngine and runner from Hampshire, Illinois. I work with php a lot; Spending most of my time digging into source code to see how it all works. You can find me on Twitter @rfmeier.

Leave a Reply

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