I now need to filter a CPT archive query by a custom field of the CPT. In this case, I have a "Business" CPT which has a "Membership Status" custom field. I want to filter the "Business" archive query to only include those businesses with the "Membership Status" field set to "Approved".
My attempt at modifying the archive query is resulting in a fatal error:
function archive_business_active_member_only( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
/* Not an admin page query but a query for the front-end of site */
/* Check for archive query of Business post-type */
if ( is_post_type_archive( 'business' ) ) {
/* Get all users with role of "Active Member" */
$user_ids = get_users( [
'role' => 'member_active',
'fields' => 'ID'
] );
/* Only include posts whose authors have the "Active Member" role */
$query->set( 'author__in', $user_ids );
/* Only include Businesses whose "Membership Status" is set to "Approved" */
$query->set = ( 'meta_key', 'membership-status' );
$query->set = ( 'meta_value', 'approved' );
$query->set = ( 'meta_compare', '=' );
/* Set the orderby to "title" and order to "ASC" to sort Business archive by ascending title */
$query->set( 'order', 'ASC' );
$query->set( 'orderby', 'title' );
}
}
}
add_action( 'pre_get_posts', 'archive_business_active_member_only' );