Searching Posts Programmatically in a WordPress Plugin

If I navigate to Posts -> All Posts in a WordPress install, there’s a Search Box in the upper right hand corner. Entering terms in this box and clicking the Search Posts button will perform a search.

Does WordPress provide a hook, function, or other API that would allow me to programmatically perform the same (or a similar) search? i.e. I pass in a string as terms and get back a PHP array of results without needing to write any SQL myself.

If not, does anyone here know where in the WordPress core code the above search happens? (so I cam mimic the behavior as best as possible)

$posts = get_posts(["s" => "string to search"]);

Count search results

On my wordpress search page I would like to show a ‘total found results’. This needs to be shown at the top of the page in a heading.

I’ve tried this code but I gives me only the results of the specific page. What I want is all the results, not just the page.

<?php echo $wp_query->post_count; ?>

 


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *