apply_filters( 'relevanssi_related_args', array $args, string $context )

This filter hook filters the query arguments for the Related Posts query.


(array) The query parameters.

(string) Which related posts query this is. Possible values are “or”, “random fill” or “random”.

More information

When Relevanssi generates the related posts, Relevanssi uses WP_Query to search for the related posts. The keywords used depend on the Related Posts settings. You can use this filter hook to modify the query parameters Relevanssi uses to fetch the posts.

For example, if you only want the Related Posts to show posts that have been published in the past 14 days and that don’t have the meta field expired set to 1, you can add this to your site:

add_filter( 'relevanssi_related_args', 'rlv_related_posts' );
function rlv_related_posts( $args ) {
  $args['meta_key']     = 'expired';
  $args['meta_value']   = '1';
  $args['meta_compare'] = '!=';
  $args['date_query']   = array(
      'after' => '14 days ago',
  return $args;

This function will limit all related posts to recent, unexpired posts.

When adjusting the parameters, do note that there are some default values you should respect. Relevanssi sets s, posts_per_page, post_type, post__not_in, fields, operator and post_status, and you should not change these values unless you are sure you know what you’re doing. For example, if you want to allow private posts in the Related Posts, you can do this:

add_filter( 'relevanssi_related_args', 'rlv_allow_private' );
function rlv_allow_private( $args ) {
  $args['post_status'] = array( 'publish', 'private' );
  return $args;

If you want to be more specific, you can use the $context parameter to tell which Related Posts query this is. The base case is “or”. If you have enabled the setting “fill with random posts”, that query has the $context “random fill”. The $context “random” is for the case where Relevanssi finds no related posts, and you’ve chosen to get a random selection.