Posted on

Private posts in custom post types

Relevanssi has some problems when it comes to checking if it can show private posts to a user, if the post is in a custom post type.

Relevanssi doesn’t actually check the what the capability to read private posts is called, but instead assumes it’s read_private_slugs, where slug is the name of the post type.

That’s a problem, if the custom post type uses a different name for the capability. Sermon manager for WordPress, for example, uses a custom post type wpcf_sermon, but the capability is read_private_posts, not read_private_wpcf_sermons.

From Premium 1.13 and Relevanssi 3.3.6 onwards, you can do this to fix this:

add_filter('relevanssi_private_cap', 'private_sermon_cap');
function private_sermon_cap($cap) {
    if ($cap == 'read_private_wpfc_sermons') $cap = 'read_private_posts';
    return $cap;
}

In earlier versions, the fix is more complicated:

add_filter('relevanssi_post_ok', 'private_sermon_post_ok', 11, 2);
function private_sermon_post_ok($post_ok, $doc) {
	$status = relevanssi_get_post_status($doc);
 
	if ('private' == $status) {
		$type = relevanssi_get_post_type($doc);
		if ($type == 'wpfc_sermon') $type = "post";
		$cap = 'read_private_' . $type . 's';
		if (current_user_can($cap)) {
			$post_ok = true;
		}
	}
 
	return $post_ok;
}

This function will run after the default check, and if the post type is wpfc_sermon and the post is private, the function will check if the user is allowed to see the post.