I'm trying to hide attachments with a taxonomy. I want to hide them from Post page in wp-admin. I can't figure out how to detect the page I'm in from ajax_query_attachments_args. I tried to use pre_get_posts, but it doesn't seem to trigger ajax_query_attachments_args.
add_filter('ajax_query_attachments_args', 'hide_attachment_with_taxonomy', 50, 1);
function hide_attachment_with_taxonomy( $query = array() ) {
global $current_screen;
if ( ! $current_screen ) {
return $query; // It always return this value. $current_screen or get_current_screen() is always undefined
}
if($current_screen->post_type == 'post'){
$query['tax_query'] = array(
array(
'taxonomy' => 'category',
'operator' => 'NOT EXISTS'
),
);
return $query;
}
}
I'm trying to hide attachments with a taxonomy. I want to hide them from Post page in wp-admin. I can't figure out how to detect the page I'm in from ajax_query_attachments_args. I tried to use pre_get_posts, but it doesn't seem to trigger ajax_query_attachments_args.
add_filter('ajax_query_attachments_args', 'hide_attachment_with_taxonomy', 50, 1);
function hide_attachment_with_taxonomy( $query = array() ) {
global $current_screen;
if ( ! $current_screen ) {
return $query; // It always return this value. $current_screen or get_current_screen() is always undefined
}
if($current_screen->post_type == 'post'){
$query['tax_query'] = array(
array(
'taxonomy' => 'category',
'operator' => 'NOT EXISTS'
),
);
return $query;
}
}
The answer is wp_get_referer(). This function is working inside ajax_query_attachments_args. I can then use get_post_type with the post id from url parameters
$referer = parse_url(wp_get_referer());
parse_str($referer['query'], $params);
if (isset($params['post'])){
$post_type = get_post_type($params['post']);
} else if (strpos($referer['path'], 'post-new.php') !== false && !isset($params['post_type'])){
$post_type = 'post';
} else {
$post_type = '';
}
if ( $post_type == 'post' ) {
$query['tax_query'] = array(
array(
'taxonomy' => 'category',
'operator' => 'NOT EXISTS'
),
);
}
$base = basename( wp_get_referer() ); if ( 'post.php' === substr( $base, 0, 8 ) ) { your code here }
– Sally CJ Commented Nov 9, 2019 at 13:49