Filtering WordPress Search Results by the Page Post Type

Tacking a post_type parameter to any search URL in WordPress filters the search results by a post type.

For example:

http://example.com/?s=speak+easy&post_type=events

Will return only events which include the terms speak and easy.

But when setting the post_type parameter to page, something unusual happens.

Publicly Queryable Pages

When you request only search results that are pages, you’ll get results of all post types. This comes about due to the publicly_queryable value for pages being set to false and a bug in core (Trac ticket).

There is an easy fix, just set publicly_queryable to true. For example:

/**
 * Sets the 'publicly_queryable' value of the page post type to true
 * so that search results can be filtered by page.
 *
 * @author Brent Shepherd
 */
function eg_make_pages_queryable() {
	global $wp_post_types;	

	$wp_post_types['page']->publicly_queryable = true;
}
add_action( 'init', 'eg_make_pages_queryable', 20 );

Changing a setting directly on the global is not ideal, but I couldn’t find an API function for changing the publicly_queryable or any other post type setting. Did I miss it?

About Brent

Born to code.
This entry was posted in WordPress and tagged , , . Bookmark the permalink.

One Response to Filtering WordPress Search Results by the Page Post Type

  1. Another great find mate.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s