Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created April 16, 2018 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumikito/27ac67f03f6940265027b76434c877e3 to your computer and use it in GitHub Desktop.
Save fumikito/27ac67f03f6940265027b76434c877e3 to your computer and use it in GitHub Desktop.
Hide specific attachments from media library.
<?php
/**
* Hide specific media from media library.
*/
/**
* Case 1. Do not allow gif.
*
* This filter will be triggered by media library's AJAX action.
*
* @param array $args Passed to WP_Query.
*/
add_filter( 'ajax_query_attachments_args', function( $args ) {
// Get all mimes from core.
$all_mimes = get_allowed_mime_tyes();
// List not allowed mimes.
$not_allowed = ['image/gif'];
$args['post_mime_type'] = $all_mimes;
return $args;
} );
/**
* Case 2. Exclusive condition with post meta.
*
* Hide attachments which has some extra post meta.
* meta_query is not available because it trys inner join.
* Let's suppose meta_key 'img_src' is not in 'twitter' and 'instagram'.
*/
// Add special query var.
add_filter( 'query_vars', function( $vars ) {
$vars[] = 'special-img';
return $vars;
} );
// Mark query var on media library.
add_filter( 'ajax_query_attachments_args', function( $args ) {
$args['special-img'] = true;
return $args;
} );
// Filter query.
add_filter( 'posts_where', function( $where, $wp_query ) {
if ( ! $wp_query->get( 'special-img' ) ) {
return $where;
}
global $wpdb;
$where .= <<<SQL
{$wpdb->posts}.ID NOT IN (
SELECT post_id FROM {$wpdb->postmeta}
WHERE meta_key = 'img_src'
AND meta_value IN ('twitter', 'instagram')
)
SQL;
return $where;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment