I'm developing a site where people can search phone number(s), the most complex part is that i want to create a post automatically when someone search for a specific number if that phone number yield zero results want to create a post with title as the searched number. this should be done without any user registration process. is there a way to achieve this?
-
Just a word of caution here, this has the potential of taking your site down. If your site is flooded with searches, you'll be creating a lot of posts. What is the intent behind this approach? – Welcher Sep 30 '20 at 13:29
Assuming you are using the standard WordPress search, you can get the searched number with get_search_query
So this code will create a new draft post if no results were found for the search:
$match = get_page_by_title( sanitize_title( get_search_query() ), OBJECT, ['post_type' => 'post'] );
if ( empty( $match ) ) {
wp_insert_post(
['post_title' => sanitize_title( get_search_query() ) ]
);
}
The above snippet would be added to the search.php
template in your theme.
-
-
This might not work as expected as the search term could also be in the post content. I'll update the answer later unless someone else does – Paul Sep 30 '20 at 8:32
-