• Resolved purrdesign

    (@purrdesign)


    Starting a new thread about the same issue as discussed here: https://www.ads-software.com/support/topic/cant-search-through-media-library/page/2/

    We’re using a similar query to exclude custom post types from site search results, but it breaks the media search in the Web Stories plugin:

    function excludePostType($query) {
    if (!$query->is_admin && $query->is_search) {
    $query->set(‘post_type’, ‘post’);
    }
    return $query;
    }
    add_filter(‘pre_get_posts’,’excludePostType’);

    We’d like to keep this code in place (have not found a suitable alternative), so I’m wondering if you can advise how to alter it to ensure the media search still works? The thread linked above mentions something about the REST API but I’m not sure how to modify the query above to exclude REST API queries.

    This is a conflict I’ve encountered before and have yet to find a good alternative to exclude custom post types, so I’m hoping we can figure out a way to modify the query instead to prevent the conflict.

    Your help would be greatly appreciated!

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Author Pascal Birchler

    (@swissspidy)

    What is it that you are trying to achieve with this code? Are you trying to exclude pages from website search results?

    If so, you should use something like this:

    add_filter(
    	'register_post_type_args',
    	static function ( $args, $name ) {
    		if ( 'page' === $name ) {
    			$args['exclude_from_search'] = true;
    		}
    
    		return $args;
    	},
    	10,
    	2
    );

    Thread Starter purrdesign

    (@purrdesign)

    I only want posts to show in my frontend site search, not pages or custom post types.

    Unfortunately the ‘exclude_from_search’ attribute causes issues with the custom post type taxonomy archive pages, which is why I prefer to use the custom query instead.

    Plugin Author Pascal Birchler

    (@swissspidy)

    I see. Well, in that case if you wanna keep your existing snippet I recommend simply not altering any REST API requests by checking for the REST_REQUEST constant.

    For example like this:

    function purrdesign_excludePostType( $query ) {
    	if (
    		! $query->is_admin &&
    		$query->is_search &&
    		( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST )
    	) {
    		$query->set( 'post_type', 'post' );
    	}
    
    	return $query;
    }
    
    add_filter( 'pre_get_posts', 'purrdesign_excludePostType' );

    Thread Starter purrdesign

    (@purrdesign)

    Yes, that worked perfectly! Exactly what I was hoping for. Thanks so much for the quick response!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Image Search not working with custom query’ is closed to new replies.