Posted on

Relevanssi and BBPress

Relevanssi does work with BBPress. BBPress forums, topics and replies are regular WordPress posts. In order to get Relevanssi working with BBPress, you need to make Relevanssi index post type “topic” (forget “forum”, and I think it’s better if you skip “reply” as well).

Since “topic” is non-public post type, you also need to uncheck the Respect exclude_from_search option.

Now these settings won’t notice replies. You could choose to index replies, but then you can get results where you have many replies from the same topic. I suggest instead skipping the replies in the indexing, but adding this code to your theme functions.php:

add_filter('relevanssi_content_to_index', 'rlv_add_replies', 10, 2);
add_filter('relevanssi_excerpt_content', 'rlv_add_replies', 10, 2);
function rlv_add_replies($content, $post) {
	if ($post->post_type == 'topic') {
		$replies = get_posts(array('post_type' => 'reply', 'post_parent' => $post->ID, 'posts_per_page' => -1));
		if (is_array($replies)) {
			foreach ($replies as $reply) {
				$content .= " " . $reply->post_content . " ";
			}
		}
	}
	return $content;
}
 
add_filter('wp_insert_post', 'rlv_index_replies');
function rlv_index_replies($post_id) {
	$post = get_post($post_id);
	if ($post->post_type == 'reply') {
		relevanssi_index_doc($post->post_parent, $remove_first = true, $custom_fields = false, $bypassglobalpost = true);
	}
}

This will add the contents of the replies to the topic posts. That way the whole conversation is indexed in one go.

The second function is also important. It makes sure that the topics are reindexed when new replies are added (this doesn’t trigger a reindex of the topic when a reply is removed; I’ll leave that as an exercise for the reader).