0

Hello i have a page with a little uploader to upload media in the library, here is my code :

            <?php 
                $post_id = $post->ID;
                if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
                    require_once(ABSPATH . 'wp-admin/includes/admin.php');
                    $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page
                    unset($_FILES);
                    if ( is_wp_error($id) ) {
                        $errors['upload_error'] = $id;
                        $id = false;
                    }

                    if ($errors) {
                        echo "<p>There was an error uploading your file.</p>";
                    } else {
                        echo "<p>Your file has been uploaded.</p>";
                    }
                }

            ?>

With my form :

<form id="file-form" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">

<p id="async-upload-wrap"><label for="async-upload">upload</label>
<input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Upload" name="html-upload"></p>

<p><input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /></p>
<p><input type="submit" value="Save all changes" name="save" style="display: none;"></p>
<form>  

And my snippet to enable category and tag to media :

// add categories for attachments
function add_categories_for_attachments() {
    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'add_categories_for_attachments' );

// add tags for attachments
function add_tags_for_attachments() {
    register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init' , 'add_tags_for_attachments' );

Everything work great. I can upload, it's working. I can select category in media library on back. Now i just want a checkbox or list to select existant category to attach them to the uploaded media before uploading.

I don't now if i'm clear but i'm not native english. :)

Thank you guys !

0

Maybe you can assign attachment to those categories after upload? Check this example.

function add_category_automatically($post_ID) {
    $attach = get_post($post_ID);
    if ($attach->post_parent) {
        $cats = get_the_category()($attach->post_parent);
        foreach ($cats as $cat) {
            wp_set_object_terms($post_ID, $cat->slug, 'category', true);
        }
    }
}
add_action('add_attachment', 'add_category_automatically');

Source

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.