Try Applying These Changes
-
Add this conditional before the
// first check if data exists with select query:// Do nothing else if the search term is empty. if ( empty( $search_term ) ) { return $where; }Update: You may also want to check if it’s the main query and if not, exit the function:
if ( empty( $search_term ) || // missing search term ! $wp_query->is_main_query() ) { // or not the main query return $where; } -
I would not
douseSELECT *(select all) records$wpdb->get_results()just to check if an existing entry for a search term exists in the database or not. Secondly, you should’ve used$wpdb->prepare()instead of theTERM = '".$search_term."'. So I’d replace this:$datum = $wpdb->get_results("SELECT * FROM search_product WHERE TERM = '".$search_term."'"); if($wpdb->num_rows > 0) {with this:
$sql = $wpdb->prepare( "SELECT TERM FROM search_product WHERE TERM = %s LIMIT 1", $search_term ); if ( $wpdb->get_var( $sql ) ) { -
Again in this code, you should’ve not used
TERM = '".$search_term."'. So I’d replace this:$sql = $wpdb->prepare( "UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = '".$search_term."'");with this:
$sql = $wpdb->prepare( "UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = %s", $search_term ); -
And the code after the
// if not exist in the database then insert itcan be rewritten to:else { $wpdb->insert( 'search_product', [ 'TERM' => $search_term, 'DATE' => current_time( 'mysql' ), // 'COUNTER' => 1, // <- uncomment if the default value of the column is not 1 ] ); }