我需要为没有特定功能的用户限制媒体库中的项目。有很多例子可以说明如何将它们限制为仅限于给定用户上传的项目,但我的需要比这更复杂。
我需要将没有特定功能的用户的媒体项目限制为以下附件:
标题图像(即在外观>标题中设置)
页面缩略图(即特色图像)下面是我提出的解决方案。/*
* restrict media items available to users without cap=mycap to those that are NOT:
*
* 1. theme headers (i.e., set in Appearance > Headers)
* 2. page thumbnails (i.e., featured images)
*/
add_action (\'pre_get_posts\', \'restrict_media\') ;
function
restrict_media ($query)
{
if (!is_admin () || $query->get (\'post_type\') != \'attachment\' ||
current_user_can (\'mycap\')) {
return ;
}
// get our theme\'s headers (i.e., set in Appearance > Headers)
$args = array (
\'post_type\' => \'attachment\',
\'post_status\' => array (\'inherit\', \'private\'),
\'posts_per_page\' => -1,
\'meta_query\' => array (
\'relation\' => \'AND\',
array (
\'key\' => \'_wp_attachment_context\',
\'value\' => \'custom-header\',
),
array (
\'key\' => \'_wp_attachment_is_custom_header\',
\'value\' => \'antelopevalley\',
),
),
) ;
// remove ourself from pre_get_posts to avoid infinite regression
remove_action (\'pre_get_posts\', array ($this, \'restrict_media\')) ;
$headers = new WP_Query ($args) ;
// get the IDs of the headers
$header_ids = array_map (function ($p) { return ($p->ID) ; }, $headers->posts) ;
// add ourself back to pre_get_posts for subsequent queries
add_action (\'pre_get_posts\', array ($this, \'restrict_media\')) ;
// get posts with thumbnails
$args = array (
\'post_type\' => \'page\',
\'post_status\' => array (\'publish\', \'pending\', \'draft\', \'private\'),
\'posts_per_page\' => -1,
\'meta_query\' => array (
array (
\'key\' => \'_thumbnail_id\',
\'compare\' => \'EXISTS\',
),
),
) ;
$with_thumbnail = new WP_Query ($args) ;
// get the IDs of the thumbnails
$thumbnail_ids = array_map (function ($p) { return (get_post_meta ($p->ID, \'_thumbnail_id\', true)) ; },
$with_thumbnail->posts) ;
// exclude all theme headers and thumbnails
$query->set (\'post__not_in\', array_merge ($header_ids, $thumbnail_ids)) ;
return ;
}
上述解决方案有效;然而,这对我来说似乎太复杂了!我想知道是否有人能提出一个更简单的解决方案。
注意:我以前尝试过post{where,join}过滤器来满足其他需求,但发现它们太复杂,无法维护,所以我甚至没有尝试使用它们来解决这个问题,但我对使用它们的人非常开放