Sql query triggered twice

Try Applying These Changes

  1. 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;
    }
    
  2. I would not do SELECT * (select all) records use $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 the TERM = '".$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 ) ) {
    
  3. 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 );
    
  4. And the code after the // if not exist in the database then insert it can 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
        ] );
    }