I develop a plugin which includes a custom post type that is displayed as a list within WP Admin.
There are varying levels of users defined within the plugin and a few other options which determine which of the posts are displayed to the currently logged in user. Additionally, posts may belong to a custom taxonomy. In this case, further conditions should determine which posts the current user sees. For example, perhaps the current user should be able to see all posts with the term Support from the Department taxonomy.
I am hooking into pre_get_posts
in order to build out the query ensuring that the current user only sees the posts they should. Admins see all, others only see posts whereby they are assigned. This is all working fine with standard meta queries.
It's the taxonomy I'm having an issue with. I understand it is not possible to create a WP Query to query posts where a meta key exists and equals a value OR the post has a specific taxonomy term associated with it, unless I build out a database query of my own.
What is the best way to do this ensuring I keep the DB queries minimal?
I've posted below my current query. I'm looking for guidance on the best hook to use and query to use in order to achieve what I need.
function kbs_restrict_agent_ticket_view( $query ) {
if ( ! is_admin() || 'kbs_ticket' != $query->get( 'post_type' ) ) {
return;
}
$admin_agents = kbs_get_option( 'admin_agents' );
if ( empty( $admin_agents ) && current_user_can( 'administrator' ) ) {
$query->set( 'p', '99999999' );
return;
}
// If user is admin and admins are agents, they see all.
if ( current_user_can( 'manage_ticket_settings' ) ) {
return;
}
if ( kbs_get_option( 'restrict_agent_view', false ) ) {
$agent_id = get_current_user_id();
$meta_query = array(
'relation' => 'OR',
array(
'key' => '_kbs_ticket_agent_id',
'value' => $agent_id,
'type' => 'NUMERIC'
),
array(
'key' => '_kbs_ticket_agent_id',
'value' => ''
),
array(
'key' => '_kbs_ticket_agent_id',
'value' => 'anything',
'compare' => 'NOT EXISTS'
)
);
if ( kbs_multiple_agents() ) {
$meta_query[] = array(
'key' => '_kbs_ticket_agents',
'value' => sprintf( ':%d;', $agent_id ),
'compare' => 'LIKE'
);
}
$query->set( 'meta_query', $meta_query );
}
} // kbs_restrict_agent_ticket_view
add_action( 'pre_get_posts', 'kbs_restrict_agent_ticket_view' );
I'm effectively now looking for OR post has term ('support', 'department')