Fix Potential Security Issue in Custom Taxonomy Search Functionality
-
Hi,
I want to add some functionality to a WordPress site that uses taxonomy terms from custom post types in the WordPress search, and come across the code given below on StackOverflow
This solution does work, but in the comments a user has mentioned that it’s “probably not a good idea to inject the raw publicly available search string directly into an SQL query” and added a link for further reading (which is way above my head).
One of the comments mentions that the answer given uses the
get_search_query()
used directly in the MySQL statement of the WHERE clause, so the code is vulnerable to SQL injection attacks, where anyone can execute arbitrary SQL queries on your site by passing them through the search field. It mentions that that this input needs to be prepared properly to ensure it is interpreted as search terms and not SQL statements. This is what the$wpdb->prepare()
method is for.Does anyone know how to integrate the
$wpdb->prepare()
into the code below (which was given in the original answer)?Many thanks
function atom_search_where($where){ global $wpdb; if (is_search()) $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')"; return $where; } function atom_search_join($join){ global $wpdb; if (is_search()) $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id"; return $join; } function atom_search_groupby($groupby){ global $wpdb; // we need to group on post ID $groupby_id = "{$wpdb->posts}.ID"; if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby; // groupby was empty, use ours if(!strlen(trim($groupby))) return $groupby_id; // wasn't empty, append ours return $groupby.", ".$groupby_id; } add_filter('posts_where','atom_search_where'); add_filter('posts_join', 'atom_search_join'); add_filter('posts_groupby', 'atom_search_groupby');
- The topic ‘Fix Potential Security Issue in Custom Taxonomy Search Functionality’ is closed to new replies.