Add Enctype To Wordpress Post And Page Forms

Saturday, March 27, 2010 - 22:25

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

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

Add new comment