Attaching media to custom posts without editor

At the top of wp-admin/edit-form-advanced.php I see the following code that seems related to the media uploader:

if ( post_type_supports($post_type, 'editor') || post_type_supports($post_type, 'thumbnail') ) {
    add_thickbox();
    wp_enqueue_script('media-upload');
}

You’ll need to add these yourself. add_thickbox() enqueues both a script and a style, so make sure you hook into print_styles, as print_scripts will be too late to also print a style.

add_action('admin_print_styles-post-new.php', 'wpa4016_add_media_upload_scripts');
add_action('admin_print_styles-post.php', 'wpa4016_add_media_upload_scripts');
function wpa4016_add_media_upload_scripts()
{
    if ($GLOBALS['post_type'] == 'wpa4016') {
        add_thickbox();
        wp_enqueue_script('media-upload');
    }
}

Now we need to add the upload buttons. I see the_editor(), the function that displays the editor, has a parameter $media_buttons, and if we set to to true it basically executes do_action('media_buttons'). This in turn calls media_buttons(), which calls _media_button() for each media type (image, video, audio, …). So we do this ourselves!

add_action('edit_form_advanced', 'wpa4016_edit_form_advanced');
function wpa4016_edit_form_advanced()
{
    if ($GLOBALS['post_type'] == 'wpa4016') {
        echo _media_button(__('Add an Image'), 'images/media-button-image.gif?ver=20100531', 'image');
    }
}

Attachments are indeed custom posts of type attachment, with their post_parent set to the post they’re attached to. Images have two meta fields: _wp_attached_file contains the filename, _wp_attachment_metadata contains an array with image EXIF data and pointers to different sizes of the same image. You can create these yourself, using wp_insert_attachment(), but I believe you still have to handle the upload yourself then.

Leave a Comment