I’m working on a custom search page and I usually use wpdb->prepare when crafting custom queries. But this time I went with get_posts to create the below query. But I’m wondering if I have to worry about SQL Injection with it. Should I? Or does get_posts() have that security built in?
If not, how do I clean the incoming variables?
$SEARCH_QUERY = @$_GET['s2'];
$args2 = array(
'orderby' => 'date',
'order' => 'DESC',
's' => $SEARCH_QUERY
);
$arrSearchResults = get_posts($args2);
echo "<pre>";
print_r($arrSearchResults);
echo "</pre>";
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If not, how do I clean the incoming variables?
In most cases you don’t, get_posts calls WP_Query internally, and WP_Query performs some sanitization, namely via wpdb->prepare.
However, for what you’re trying to do, this is the wrong approach. Just use a standard search.php template with a standard post loop, and use input fields that have the same names as the parameters for WP_Query. WP will automatically filter as a result of them being added to the URL. There is no need for a custom page template with a custom query and custom URL parameters. It’s just unnecessary complexity, and double the database queries ( don’t forget the broken pagination, dealing with 404’s, etc )
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0