Gerand
Forum Replies Created
-
Forum: Plugins
In reply to: [Enhanced Media Library] Programmatically pre-set Media Categories [feature]Thank you for the reply!
I ended up making a temporary solution that sets a predefined term to the attachment when it is inserted via the uploader.
We decided it had to be done when inserted and not when uploaded (suits best for our purpose).I put a script in the admin footer that runs whenever a click is triggered on some pre-selected elements.
It checks for the attribute “data-media-category” on the element, if it doesn’t have it we return nothing.
It then overrides the wp.media.editor.send.attachment function, fetches the attachment id and sends that plus the media-category defined by the attribute via an ajax request.
Then I set the term to the attachment id on the receiving end.All I have to do is add the attribute ‘data-media-category=”blablabla”‘ to the buttons.
ATM it only supports one taxonomy, namely media_category.It may not be the best solution but I had to do something quickly to make inserted items to specific fields “auto get” categories, so it works for now =)
add_action( 'wp_ajax_gr_add_media_category', 'gr_auto_media_category_ajax' ); function gr_auto_media_category_ajax() { $attachment_id = ( isset( $_POST['attachment_id'] ) ) ? $_POST['attachment_id'] : ""; $term_slug = ( isset( $_POST['term_slug'] ) ) ? $_POST['term_slug'] : ""; gr_auto_media_category( $attachment_id, $term_slug ); die(); } function gr_auto_media_category( $attachment_id, $term_slug ) { if ( !is_numeric( $attachment_id ) || empty( $term_slug ) ) return; $result = wp_set_object_terms( $attachment_id, $term_slug, 'media_category', true ); } add_action( 'admin_print_footer_scripts', 'gr_auto_media_category_script' ); function gr_auto_media_category_script() { ?> <script type="text/javascript"> function grSetMediaCategoryForPostAttachment( term_slug, attachment_id ) { jQuery.post(ajaxurl, { action : "gr_add_media_category", attachment_id : attachment_id, term_slug : term_slug }, function() {}); } jQuery("document").ready(function(){ jQuery(document).on("click", 'button, input[type="submit"], .button, .button-primary, .button-small, .button-large', function(){ if ( jQuery(this).is("[data-media-category]") != true ) return; var add_media_category = jQuery(this).attr("data-media-category"); var gr_origin_send_attachment = wp.media.editor.send.attachment; wp.media.editor.send.attachment = function(props, attachment){ grSetMediaCategoryForPostAttachment( add_media_category, attachment.id ); return gr_origin_send_attachment.apply( this, [props, attachment] ); } }); }); </script> <?php }