There are few issue with your code
-
When using
WP_Queryin conjuction withthe_post()or usingget_posts()in conjuction withsetup_postdata( $post ), you need to reset the$postglobal withwp_reset_postdata(), notwp_reset_query().wp_reset_query()is used in conjuction withquery_posts()which you should never ever use -
You would want to reset posdata between your
endwhileandendifstatements. If you don’t have any posts, there is no need to reset$postas you have never changed it. -
Where possible, you should avoid using globals. Globals are evil. WordPress has already made such a huge mess of it. Don’t dirty global space any further. There are a couple of excellent posts on-site with extremely good alternatives to using globals. Be sure to make use of the on-site search function
-
pre_get_postsalters all queries, front end and back end. You will specifically need to target a specific query on a specific page to avoid unexpected behavior. If you only need to target the main query on your search pahe, you will need to add the following conditionsif ( !$query->is_main_query() // Bail if this is not the main query && !$query->is_search() // Bail if this is not the search page ) { return; } -
Never ever make use of unsanitized data coming from form inputs or from super globals. These are popular places which is used by hackers to inject malicious code into a website. ALWAYS ALWAYS sanitize, validate and/or escape any user supplied data according to the type of data you expect. Don’t even trust your own input. A simple piece of code injected into a URL or a form field can give a hacker full access to your site which will compromise your complete site. If you are running a site with personal info, you can land yourself in jail for leaking personal info. So please, ALWAYS SANITIZE, VALIDATE AND ESCAPE APPROPRIATELY