WordPress.org

Ready to get started?Download WordPress

Forums

Relevanssi - A Better Search
[resolved] Exclude child posts (7 posts)

  1. xave
    Member
    Posted 1 year ago #

    Is it possible to exclude child posts of a custom post type from search results.
    ie only show results of pages and posts and custom post type where parent = 0

    many thanks.

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

  2. Mikko Saari
    Member
    Plugin Author

    Posted 1 year ago #

    Anything is possible when using the relevanssi_hit_filter filter hook. Simply create a function that removes all child posts from the search results.

  3. xave
    Member
    Posted 1 year ago #

    Hi

    I've been unsuccessful writing the filter.

    add_filter('relevanssi_modify_wp_query', 'mod_q');
    function mod_q($wp_query) {
    	if (is_search()) {
    		global $wp_query;
    		$wp_query->query_vars['post_parent'] = 0;
    	}
    	return $wp_query;
    }

    Could you offer any guidence to simply filter out any child posts from a search.
    many thanks

  4. Mikko Saari
    Member
    Plugin Author

    Posted 1 year ago #

    Relevanssi does not care about $wp_query->query_vars['post_parent'].

    Like I said, relevanssi_hits_filter is your friend here:

    add_filter('relevanssi_hits_filter', 'no_kids_allowed');
    function no_kids_allowed($hits) {
        $all_children_left_behind = array();
        foreach ($hits[0] as $post) {
            if ($post->post_parent == 0) $all_children_left_behind[] = $post;
        }
        return $all_children_left_behind;
    }
  5. xave
    Member
    Posted 1 year ago #

    Thanks Mikko -
    However, the filter is returning error:

    PHP Fatal error: Cannot use object of type stdClass as array in .../relevanssi/lib/search.php on line 918

  6. xave
    Member
    Posted 1 year ago #

    Fixed: Seems I just needed to return $all_children_left_behind as an array!

    add_filter('relevanssi_hits_filter', 'no_kids_allowed');
    function no_kids_allowed($hits) {
        $all_children_left_behind = array();
        foreach ($hits[0] as $post) {
            if ($post->post_parent == 0) $all_children_left_behind[] = $post;
        }
        return array($all_children_left_behind);
    }

    Many thanks - saved the day!

  7. Mikko Saari
    Member
    Plugin Author

    Posted 1 year ago #

    Ah, yes, sorry about that - the filter does expect the result in an array. Glad you got it sorted out.

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic