October 24, 2024
Chicago 12, Melborne City, USA
PHP

Visual Studio Code reports warnings on all $wpdb methods


While writing a plugin in WordPress using Visual Studio Code, I get warnings for every use of the $wpdb global object. The code executes fine, but the warnings are irritating and clutter the IDE

Here is the warning:

Call to a member function get_var() on a non-object of type null

It’s as though VSCode thinks the $wpdb object is type null when in fact it’s a defined global object. Is there a way to better define its type to avoid the warning?

In the Visual Studio IDE, "get_var" and "last_error" are underlined in yellow, and show as a warning in the "Problems" pane.

function test() {
    global $wpdb;
    
    $sql = "SELECT firstname FROM users WHERE id=1";
    $result = $wpdb->get_var($sql);
    if ($wpdb->last_error) { 
        throw new Exception($wpdb->last_error); 
    }

    echo $result;
}

Screenshot:
enter image description here



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video