I’d really like to get rid of the messages about coding style
Despite not recommended, you can ignore/whitelist warnings and errors for a line or block of code using special PHPCS/WPCS comments which you can find here:
Working examples: ( Note: WordPress accepts all these syntaxes without giving any errors/warnings, however, it’s WPCS which does not accept them 😅 )
-
This uses
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
to ignore this error: “Use placeholders and $wpdb->prepare(); found …“$keys = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 'SELECT * FROM ' . self::MAP_KEY_TABLE . ' WHERE key_type = "map_key"', OBJECT );
-
This uses
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder
to ignore this warning: “Complex placeholders used for values in the query string in $wpdb->prepare() will NOT be quoted automagically. Found: …” (see also lines 25-27 there)$keys = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnquotedComplexPlaceholder 'SELECT * FROM %1$s WHERE key_type = "map_key"', self::MAP_KEY_TABLE ), OBJECT );
-
This uses
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
to ignore this error: “Use placeholders and $wpdb->prepare(); found interpolated variable …“$table = self::MAP_KEY_TABLE; $keys = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT * FROM $table WHERE key_type="map_key"", OBJECT );
A better solution, or a trick, which does not result in those warnings/errors
-
Add the table name as a property in the global
$wpdb
object, i.e.$wpdb->eds_map_keys = self::MAP_KEY_TABLE;
. -
Then use that in your SQL commands, e.g.
FROM $wpdb->eds_map_keys
.
This works because WPCS allows $wpdb->
. (Otherwise, you would not be able to use $wpdb->posts
, $wpdb->postmeta
, $wpdb->terms
, etc. which references the core tables in WordPress)
However, note that $this->eds_map_keys
(which could be a private property) or $some_other_object->eds_map_keys
will not work, i.e. not accepted by WPCS.
Additional Notes regarding the first parameter for $wpdb->prepare()
-
The documentation stated that “for compatibility with old behavior, numbered or formatted string placeholders (eg,
%1$s
,%5s
) will not have quotes added by this function, so should be passed with appropriate quotes around them“.And unfortunately, at the time of writing, WPCS will not accept them when used for table names, e.g.
FROM %1$s
orFROM `%1$s`
will result in theUnquotedComplexPlaceholder
error. -
The correct argument swapping format is
%<number>$s
(note the$
) and not%<number>s
. So as I commented, you should use%1$s
instead of%1s
.See the PHP manual for more details.