Create Wordpress Theme From Scratch! Build Your Own

Search custom post type by title in WordPress

webapps log

webapps Lab
June 21, 2021

This post shows how to search custom post types in WordPress using get_page_by_title.

The returned page displays the posts of the selected category.

A user will be able to see the related posts on a single page once the post type title is searched.

Also, you will find out how to search a custom post type by a posts title

Let’s get started.

using get_page_by_title

Pass the string representing the taxonomy title to a get_page_by_title.

It is a required parameter.

Let’s assume the blog has a page named “THE BEST IN TOWNS”

To retrieve the given page a page title is going to be the first parameter.

$CustomPageType = get_page_by_title (‘THE BEST IN TOWNS’);

echo $CustomPageType;

But the function ignores the post status then the best is to build a custom query.

Method 2: Using the custom query

This method requires a function in the function.php file

It also uses the add_filter function to execute a newly added function.

Here is a code snippet for the given task.

function customPostTitleSearch($query)



$args = array ( ‘post_type’, ‘about’, ‘best towns’, ‘best phones’);

$query – >set (‘post_type’, $args);


return $query;


add_filter (‘pre_get_posts’ , ‘customPostTitleSearch’);

The snippet provides a custom post type but it doesn’t return the exact match page title.

Code Explanation

To access the post a WP_Query is needed.

The function you add in functions.php takes in WP_Query object.

Otherwise, it will be difficult to achieve the object.

That is why the function parameter is $query which is the object of WP_Query class.

Another required WordPress function is add_filter.

The add_filter uses pre_get_posts to fire the created query variable.

The $query is needed to access the is_search variable and set function.

  1. is_search – You should check the kind of query returned. is_search helps determine if the query is designed to search the contents
  2. set – It sets the values of the queried variable meaning the titles of the custom page type are defined here.

The values that go to the set function are defined in an array.

The name of the array is $args.

The array contains a post_type variable that sets the kind of page the query can return.

The other members of the array are the titles of the custom post types.

The function returns the $query object which will give post types titles posts.

Some useful insights.

How to add search pagination

Create dynamic pagination