WordPress.org

Forums

Search is recognizing pages as posts (4 posts)

  1. mikeque
    Member
    Posted 5 years ago #

    I have been working on filtering the search of a WP site I am redesigning. I have been trying out different plugins and coding hacks to keep pages and specific post categories out of the search results. For some reason it regards all of my pages as being assigned to the default Post category and shows those in the search results as belonging to that category.

    Not sure where this bug comes from.

    Has anyone else encountered this problem, and even better, does anyone know of a solution?

    Thanks

  2. mikeque
    Member
    Posted 5 years ago #

    I noticed that I am also getting items from the media library in the results too

  3. lxg
    Member
    Posted 5 years ago #

    Bit of an old post, but I think that there are enough people with the same problem, so I'll just post the solution.

    You must know that this behaviour is on purpose. But the solution is quite simple. Put the following code into a file named dontsearchpages.php, upload it to your plugins directory and activate it on the Plugins page of your blog.

    <?php
    
    /*
    Plugin Name: Don't search pages
    Plugin URI: http://lxg.de
    Description: Disable searching of pages.
    Version: 0.1
    Author: Alex Günsche
    Author URI: http://lxg.de
    */
    
    function lxg_dontsearchpages($query)
    {
    	if (is_search())
    		$query = str_replace
    			("AND wp_posts.post_type != 'revision'",
    			"AND wp_posts.post_type != 'revision' AND wp_posts.post_type != 'page'",
    			$query);
    
    	return $query;
    }
    
    add_filter('posts_where', 'lxg_dontsearchpages');
    
    ?>

    Tested with WP 2.9.1 – may not work with earlier or later versions, as this is quite a dirty hack.

    Inspired by an early WordPress plugin called Search Pages – which did the opposite of this one, back when WordPress didn't search posts. :)

  4. Mark / t31os
    Moderator
    Posted 5 years ago #

    Just declare the post_type in the query_posts line of your theme's search.php as you would with any other query vars in other template files..

    'post_type=post'
    or
    'post_type' => 'post'

    Depending on whether you load the parameters as a string or array..

    Example:

    // Code below - first line of code always loses indentation on forum, hence this line first.
    
    	// Our/your args
    	$args = array( 'post_type' =>'post' );
    	// Merge with existing query if one exists
    	$args = ( $wp_query && !empty( $wp_query->query ) ) ? array_merge( $wp_query->query , $args ) : $args;
    	// Do the query
    	query_posts( $args );

Topic Closed

This topic has been closed to new replies.

About this Topic