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?
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?
Share Improve this question asked Sep 30, 2020 at 3:59 greenarrowgreenarrow 133 bronze badges 1- 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 Commented Sep 30, 2020 at 13:29
1 Answer
Reset to default 0Assuming 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.