Remove “From computer” media tab for posts with existing attachments?
-
16-10-2019 - |
Question
On editing the attachments of a post whith at least one attachment previously uploaded, how do I remove the From computer tab and redirect to the Gallery tab?
This is my current code:
add_filter('media_upload_tabs','remove_medialibrary_tabs', 99);
function remove_medialibrary_tabs($tabs) {
if ($post_id = (isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : false)) {
if (count(get_posts("post_type=attachment&post_parent={$post_id}"))>0) {
// MY QUESTION
}
}
unset($tabs['type_url']);
unset($tabs['library']);
return $tabs;
}
Solution
To remove the From Computer tab header, you unset the type
key from that array. However, this will (confusingly) not remove the tab content, and because this is the default tab it will show it even if the tab header for it is gone.
To change the default tab you must hook into the media_upload_default_tab
filter. This gets called in multiple places, I did not research which one is called in which circumstances, so I moved the check for attachments to a separate function and rewrote your code like this:
add_filter('media_upload_tabs','wpse13567_media_upload_tabs', 99);
function wpse13567_media_upload_tabs( $tabs ) {
if ( wpse13567_post_has_attachments() ) {
unset( $tabs['type'] );
}
unset( $tabs['type_url'] );
unset( $tabs['library'] );
return $tabs;
}
add_filter( 'media_upload_default_tab', 'wpse13567_media_upload_default_tab' );
function wpse13567_media_upload_default_tab( $tab )
{
if ( wpse13567_post_has_attachments() ) {
return 'gallery';
}
return $tab;
}
function wpse13567_post_has_attachments()
{
static $post_has_attachments = null;
if ( null === $post_has_attachments && $post_id = (isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : false) ) {
$post_has_attachments = count(get_posts("post_type=attachment&post_parent={$post_id}"))>0;
}
return $post_has_attachments;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange