Add Enctype To Wordpress Post And Page Forms

Whilst creating a small plugin on a Wordpress site I decided not to use the media library as I just wanted to add some small stub images to the content. I created some boxes on the post page using add_meta_box() and added a file input box to them. The only thing is that the post form in Wordpress doesn't have the enctype="multipart/form-data" attribute and so it won't pass file to the $_FILES array in PHP.

It is not possible to add the enctype into the form declaration via Wordpress as there is no hook or action to do this. So the only alternative (rather than hack the source code) is to add the attribute using JavaScript, and as we have JQuery already loaded we can utilise that.

One final issue we need to overcome is that IE doesn't seem to understand the enctype attribute so we need to add a encoding="multipart/form-data" for IE. The good news is that there is no ill effect for any browser (including IE) of adding both the enctype and encoding attributes at the same time.

Here is the code I used to add enctype, just add it to your plugin. It detects if you are looking at a page that will create or edit a post or page and then adds the necessary JQuery to the header to add the enctype attribute to the form.

if (is_admin()) {
  $current_admin_page = substr(strrchr($_SERVER['PHP_SELF'], '/'), 1, -4);
  if ($current_admin_page == 'page' 
    || $current_admin_page == 'page-new' 
    || $current_admin_page == 'post' 
    || $current_admin_page == 'post-new') {

    /** Need to force the form to have the correct enctype. */
    function add_post_enctype() {
      echo "<script type=\"text/javascript\">
        jQuery(document).ready(function(){
        jQuery('#post').attr('enctype','multipart/form-data');
        jQuery('#post').attr('encoding', 'multipart/form-data');
        });
        </script>";
    }

    add_action('admin_head', 'add_post_enctype');
  }
}

This technique will also work for any similar situation outside of Wordpress.

Comments

Thanks for posting this. Just what I was looking for!

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.