Relevanssi - A Better Search
[resolved] How to filter by post_parent (3 posts)

  1. drewshen
    Posted 1 year ago #

    I have a number of search forms on different pages in my WordPress installation. Based on the page the user is on, these need to filter by the post_parent, which serves as a category in a sense. I have added a hidden field to the search form for 'post_parent' so I can pass this value in to the search. This was all working fine with default WP searching, using 'pre_get_posts' filter.

    I added Relevanssi in order to be able to sort by relevance, and the filtering by post_parent now no longer works. I simply switched 'pre_get_posts' to call 'relevanssi_modify_wp_query':

    function filter_search_by_parent($query) {
        if ($query->is_search) {
            if (isset($_GET['post_parent']) && ($_GET['post_parent'] != 0)) {
                $query->set( 'post_parent', $_GET['post_parent'] );
                $query->set('post_type', 'page');
            } else {
                $query->set('post_type', 'post');
        return $query;
    add_filter('relevanssi_modify_wp_query', 'filter_search_by_parent');

    What is the proper way to accomplish this with Relevanssi?

    Any help is appreciated.


  2. Mikko Saari
    Plugin Author

    Posted 1 year ago #

    Relevanssi doesn't recognize "post_parent" - it didn't seem significant, when I was adding WP_Query variables to Relevanssi.

    I would recommend using relevanssi_hits_filter, something like this:

    add_filter('relevanssi_hits_filter', 'post_parent_filter');
    function post_parent_filter($hits) {
        global $wp_query;
        if (isset($_GET['post_parent']) && ($_GET['post_parent'] != 0)) {
        	$right_parent = array();
        	foreach ($hits[0] as $hit) {
        		if ($hit->post_parent == $_GET['post_parent']) $right_parent[] = $hit;
        	$hits[0] = $right_parent;
        return $hits;
  3. drewshen
    Posted 1 year ago #

    @Mikko this makes sense. Thanks for the response!

Topic Closed

This topic has been closed to new replies.

About this Plugin

  • Relevanssi - A Better Search
  • Frequently Asked Questions
  • Support Threads
  • Reviews

About this Topic