WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. drewshen
    Member
    Posted 10 months 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('pre_get_posts','filter_search_by_parent');
    add_filter('relevanssi_modify_wp_query', 'filter_search_by_parent');

    What is the proper way to accomplish this with Relevanssi?

    Any help is appreciated.

    http://wordpress.org/plugins/relevanssi/

  2. Mikko Saari
    Member
    Plugin Author

    Posted 10 months 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
    Member
    Posted 10 months ago #

    @Mikko this makes sense. Thanks for the response!

Reply

You must log in to post.

About this Plugin

About this Topic