wp-admin search posts by title only and show sub pages

I’ve got a custom post type that in the CMS I would to be able to alter the search so it only searches by title of the post, then also pulls through all sub pages of that page.

Currently I have the following, which does limit search to title but I’m struggling how to best approach pulling through the subpages and returning them on this query.

add_filter( 'posts_search', 'admin_search_shops', null, 2 );
function admin_search_shops( $search, $a_wp_query ) {

    if ( !is_admin() ) return $search;

    $search = preg_replace( "# OR (.*posts.post_content LIKE '%.*%')#", "", $search );

    return $search;
}

Related posts

1 comment

  1. Rather than trying to reconstruct a complicated SQL query, it would be much simpler to add the children in the ‘posts_results’ filter at the end. Combined with what you have done already (limiting the search to the titles), the following will add in any child pages.

        add_filter( 'posts_results', 'admin_postsearch_shops', null, 2);
        function admin_postsearch_shops( $posts ) {
            foreach( $posts as $post ) {
                $args = array( 'post_parent' => $post->ID);
                foreach ( get_children( $args ) as $child ) {
                    $posts[] = $child;
                }
            }
            return $posts;
        }
    

Comments are closed.