Posted on

Restricting posts in the index

The relevanssi_indexing_restriction filter hook is often the best way to restrict what goes in the Relevanssi index and what not. There’s also relevanssi_do_not_index, which is also a fine way to approach this and is often easier to apply when you’re talking about blocking individual posts, but for larger exclusions, relevanssi_indexing_restriction is better.

Extensive use of relevanssi_do_not_index may cause the Relevanssi indexing process to get stuck, when the indexer only gets excluded posts and can’t proceed. The relevanssi_indexing_restriction filter is safer, because it makes Relevanssi completely skip the excluded posts; they aren’t even considered. It will also make the indexing process faster.

The downside is that the exclusions must be formulated as MySQL WHERE clauses. In some cases that’s easy, in other cases difficult and in some cases impossible. Whenever it’s convenient, this is the best way to exclude posts.

Examples

Only include one category

add_filter( 'relevanssi_indexing_restriction', 'rlv_only_index_category_x' );
function rlv_only_index_category_x( $restriction ) {
	global $wpdb;
	$restriction['mysql']  .= " AND post.ID IN (SELECT tr.object_id FROM $wpdb->term_relationships AS tr, $wpdb->term_taxonomy AS tt WHERE tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.term_id = X ) "; // replace X with the category ID
	$restriction['reason'] .= ' Not in the right category';
	return $restriction;
}

Exclude one category

add_filter( 'relevanssi_indexing_restriction', 'rlv_exclude_category_x' );
function rlv_exclude_category_x( $restriction ) {
	global $wpdb;
	$restriction['mysql']  .= " AND post.ID NOT IN (SELECT tr.object_id FROM $wpdb->term_relationships AS tr, $wpdb->term_taxonomy AS tt WHERE tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.term_id = X ) "; // replace X with the category ID
	$restriction['reason'] .= ' In the wrong category';
	return $restriction;
}

More examples will be added later. Requests for examples are welcome, please leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.