How to upload an image to a custom post type

The question:

I am developing a plugin that has a custom post type. This post has a lot of meta data but I also need to attach some images to this post. What is the best way to upload an image that is related to my custom post type? I have seen some functions like media_handle_upload() and media_sideload_image() but I don’t know if they are the best solution and if so how to implement them in my code.
For the text fields I use this format

foreach ( $screens as $screen ) {
    add_meta_box(
        'give_step2',
        'Step 2',
        'meta_step_2_html',
        $screen 
    );
}

function meta_step_2_html( $post ) {
?>
    <div>
        <label for="give_desc">Description</label>
        <?php wp_editor( 'Test 123', 'give_desc'); ?>
    </div>
<?php}

if ( array_key_exists( 'give_desc', $_POST ) ) {
    update_post_meta(
        $post_id,
        'give_desc_key',
        $_POST['give_desc']
    );

*Without the hooks and the parent functions/calls

How could I implement a file upload that is consistant with this type of code without using another plugin?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

May be this thread could be useful to you:

Also you could explain a bit more what’s the pourpouse of those images. Are they going to be printed in the fontend or in the admin side? Do you need them to be uploaded from the frontend or they can be retrived from the wordpress media uploads ?

If so, you could create a src field in order to get the image source and then print it in the front end.


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

Leave a Comment