Skip to content

Customizable sniff properties

Juliette edited this page Dec 26, 2018 · 51 revisions
Clone this wiki locally

The behaviour of some sniffs can be changed by setting certain sniff properties in your ruleset. On this page you will find the properties used in the WPCS sniff library which are available for customization.

For more information about changing sniff behaviour by customizing your ruleset and how to pass different types of values via the ruleset, please read the PHPCS Annotated ruleset wiki page.

As of PHP_CodeSniffer 3.3.0, a new format is supported for passing array properties to PHPCS from a custom ruleset. This new format is fully supported by WPCS. For details, please see the PHPCS 3.3.0 release notes. You are encouraged to upgrade your custom ruleset to the new format. Support for the old format will be removed in PHP_CodeSniffer 4.0.

Array properties passed in from a custom ruleset need to have a type="array" attribute. WPCS was lenient when this attribute was missing and would convert an array passed as a comma delimited string to an array. However, this behaviour was deprecated in WPCS 1.0.0 and as of WPCS 2.0, support for incorrectly passed array properties has been removed.

WPCS also uses a number of upstream PHPCS native sniffs. For a list of customizable sniff properties for these upstream sniffs, please see the PHPCS Customisable Sniff Properties wiki page.

Table of contents

Properties strongly recommended to be set

Internationalization: setting your text domain

WordPress Sniff Property name Property type Available since:
WP.I18n text_domain array 0.10.0

The WordPress.WP.I18n sniff can optionally verify if all I18n function calls contain a $text_domain argument and whether the value of the $text_domain argument is valid. To execute this check one or more text-domains which should be considered valid must be provided in the $text_domain property in your custom ruleset or via the command-line.

If this property is not set, these checks will be skipped.

<rule ref="WordPress.WP.I18n">
	<properties>
		<property name="text_domain" type="array">
			<element value="my-text-domain"/>
			<element value="tgmpa"/>
		</property>
	</properties>
</rule>

Setting text_domain from the command line (WPCS 0.11.0+)

This property can also be set from the command line.

To set the property from the command line, use --runtime-set text_domain and pass a comma delimited list without spaces.

phpcs -p . --standard=WordPress --runtime-set text_domain my-slug,default

back to top

Naming Conventions: prefix everything in the global namespace

WordPress Sniff Property name Property type Available since:
NamingConventions.PrefixAllGlobals prefixes array 0.12.0

Prefixing all functions, namespaces, classes, interfaces, traits, variables, constants and hook names which are declared/defined in the global namespace is considered best practice to prevent naming collisions what with there being so many plugins and themes out there in the wider WordPress arena.

The WordPress.NamingConventions.PrefixAllGlobals sniff can verify that prefixes are used in all the appropriate places.

To execute this check one or more prefixes which should be considered valid must be provided via the $prefixes property in your custom ruleset or via the command-line.

If this property is not set, this sniff will not run.

<rule ref="WordPress.NamingConventions.PrefixAllGlobals">
	<properties>
		<property name="prefixes" type="array">
			<element value="my_prefix"/>
			<element value="tgmpa"/>
		</property>

	</properties>
</rule>

Setting prefixes from the command line

This property can also be set from the command line.

To set the property from the command line, use --runtime-set prefixes and pass a comma delimited list without spaces.

phpcs -p . --standard=WordPress --runtime-set prefixes my_prefix,tgmpa

back to top

Minimum WP version to check for usage of deprecated functions, classes and function parameters

WordPress Sniff Property name Property type Available since:
WP.AlternativeFunctions minimum_supported_version string 1.0.0
WP.DeprecatedFunctions minimum_supported_version string 0.11.0
WP.DeprecatedClasses minimum_supported_version string 0.12.0
WP.DeprecatedParameters minimum_supported_version string 0.12.0
WP.DeprecatedParameterValues minimum_supported_version string 1.0.0

The WordPress.WP.DeprecatedFunctions, WordPress.WP.DeprecatedClasses, WordPress.WP.DeprecatedParameters and WordPress.WP.DeprecatedParameterValues sniffs check for usage of deprecated WordPress functions and function parameters.

For deprecations before the minimum_supported_version it will throw an error. For deprecations between the minimum_supported_version and the current release (inclusive), it will throw a warning.

For example: the function add_object_page() was deprecated in WP 4.5. If usage of this function is detected, the sniff will throw an error if the minimum_supported_version is 4.6 or higher. It will throw a warning if the minimum_supported_version is 4.5 or lower.

Along the same lines, the WordPress.WP.AlternativeFunctions sniff will recommend WP alternatives for native PHP functions and will take the minimum_supported_version into account to make sure that the WP alternative is available in that version.

By default, the value of the minimum_supported_version property is set to three versions before the currently released WP version (disregarding patch releases).

For example: at the time of writing, the latest released WP version is 5.0.2, so the default value of the minimum_supported_version property is currently 4.7.

<rule ref="WordPress.WP.DeprecatedFunctions">
	<properties>
		<property name="minimum_supported_version" value="4.0"/>
	</properties>
</rule>

Setting minimum supported WP version for all sniffs in one go (WPCS 0.14.0+)

As this property becomes available to more and more sniffs and - in nearly all cases -, the same minimum supported WP version should be used for all sniffs using this property, the ability to set the minimum version via a configuration variable has been added to the sniff.

Important: The value passed to this configuration variable will take priority over the property value set for individual sniffs.

<config name="minimum_supported_wp_version" value="4.5"/>

Setting minimum supported WP version from the command line (WPCS 0.14.0+)

Setting the property in one go for all sniffs via a configuration variable can also be done from the command line.

To set the property from the command line, use --runtime-set minimum_supported_wp_version and pass the version number.

phpcs . --standard=WordPress --runtime-set minimum_supported_wp_version 4.5

back to top

Themes: allow filename exceptions

WordPress Sniff Property name Property type Default: Available since:
Files.FileName is_theme bool false 0.11.0

The WordPress PHP Coding Standards Handbook states:

Files should be named descriptively using lowercase letters. Hyphens should separate words.

While this is true for most files, there are some typical exceptions to this rule in the theme hierarchy, such as taxonomy-{custom_taxonomy}.php or archive-{post_type}.php.

By default, those exceptions will not be taken into account and will trigger an error.

If the project you're working on is a theme, you can set the is_theme property to true to allow theme hierarchy specific file name exceptions.

<rule ref="WordPress.Files.FileName">
	<properties>
		<property name="is_theme" value="true"/>
	</properties>
</rule>

back to top

Custom Unit test classes

WordPress Sniff Property name Property type Available since:
Files.Filename custom_test_class_whitelist array 0.12.0
NamingConventions.PrefixAllGlobals custom_test_class_whitelist array 0.12.0
WP.GlobalVariablesOverride custom_test_class_whitelist array 0.11.0

Certain rules can be regarded as over-zealous when applied to unit tests as these files are not part of the code which will be executed via WordPress.

To that end, any classes which extend either PHPUnit_Framework_TestCase, PHPUnit\Framework\TestCase, WP_UnitTestCase or any of the other WordPress native test cases, are whitelisted for the purpose of those specific checks.

To be specific, at this moment exceptions are made for:

  • Global Variable overrides in test classes: Sometimes WordPress global variables will need to be overloaded in unit test situations. The sniff allows for this.
  • The class-based file name rule may conflict with your PHPUnit configuration, therefore test classes are exempt from this rule.
  • No need to prefix your test classes/functions etc defined in the global namespace. As these are not executed by WordPress, there is no risk of naming collisions.

In your WordPress application you may use a custom unit test base class.

The custom_test_class_whitelist property allows you to whitelist the names of additional test classes.

It is recommended that you use the same lists for all sniffs which support this property.

<rule ref="WordPress.WP.GlobalVariablesOverride">
	<properties>
		<property name="custom_test_class_whitelist" type="array">
			<element value="My_Plugin_TestCase"/>
			<element value="My_Other_Plugin_TestCase"/>
		</property>
	</properties>
</rule>

back to top

Optional properties

Excluding a group of checks

WordPress Sniff Property name Property type Available since: Groups:
DB.RestrictedClasses exclude array 0.10.0 mysql
DB.RestrictedFunctions exclude array 0.10.0 mysql
DB.SlowDBQuery exclude array 0.3.0 slow_db_query
PHP.DevelopmentFunctions exclude array 0.11.0 error_log, prevent_path_disclosure
PHP.DiscouragedPHPFunctions exclude array 0.11.0 serialize, urlencode, runtime_configuration, system_calls, obfuscation
PHP.DontExtract exclude array 0.10.0 extract
PHP.POSIXFunctions exclude array 0.10.0 ereg, ereg_replace, split
PHP.RestrictedPHPFunctions exclude array 0.14.0 create_function
Security.SafeRedirect exclude array 1.0.0 wp_redirect
WP.AlternativeFunctions exclude array 0.11.0 curl, parse_url, json_encode, file_get_contents, file_system_read, strip_tags (since 1.0.0), rand_seeding (since 1.0.0), rand (since 1.0.0)
WP.DiscouragedFunctions exclude array 0.11.0 query_posts, wp_reset_query
WP.PostsPerPage exclude array 1.0.0 posts_per_page
WP.TimezoneChange exclude array 0.11.0 timezone_change
WP.DeprecatedFunctions exclude array 0.11.0 deprecated_functions The deprecated function checks can be disabled for each function individually by their sniff error code.
WP.DeprecatedClasses exclude array 0.12.0 deprecated_classes The deprecated classes checks can be disabled for each class individually by their sniff error code.

There are a number of sniffs which use groups of functions, classes or array keys as the basis for their checks. The grouping is normally based on functionality.

For example: the error_log group in the WordPress.PHP.DevelopmentFunctions sniff, checks for a number of error handling related functions, such as error_log(), var_dump(), print_r(), debug_backtrace() and more.

One sniff can handle the checks for an unlimited number of groups. The groups currently handled by each sniff are listed in the table above.

The exclude property allows you to disable the checks for one or more groups, without disabling the sniff completely.

To find out which group a particular function belongs to, have a look at the source code of the sniff or run PHPCS with the -s option to see the error codes. A code will look like Standard.Category.Sniff.ErrorCode. The group name will be the first part of the errorCode.

The groups to be excluded should be provided as an array.

<!-- Exclude one group. -->
<rule ref="WordPress.WP.DiscouragedFunctions">
	<properties>
		<property name="exclude" type="array">
			<element value="query_posts"/>
		</property>
	</properties>
</rule>

<!-- Exclude multiple groups. -->
<rule ref="WordPress.WP.DiscouragedFunctions">
	<properties>
		<property name="exclude" type="array">
			<element value="query_posts"/>
			<element value="wp_reset_query"/>
		</property>
	</properties>
</rule>

If you don't want to disable a complete group, but only want to disable the message for one particular check from a group, you can use the <exclude name="Standard.Category.Sniff.ErrorCode"> syntax in your ruleset.

Note: If a sniff using this property only supplies one group, excluding that group will effectively disable the sniff. Using the exclude property rather than disabling the complete sniff, however, future proofs your ruleset for when more groups would be added to the sniff in the future.

back to top

Disregard class file name rules

WordPress Sniff Property name Property type Default: Available since:
Files.FileName strict_class_file_names bool true 0.11.0

The WordPress PHP Coding Standards Handbook states:

Class file names should be based on the class name with class- prepended and the underscores in the class name replaced with hyphens.

This rule applies to WP core, but you may want to deviate from it for personal projects.

This check is turned on by default. To turn it off, set the strict_class_file_names property to false.

<rule ref="WordPress.Files.FileName">
	<properties>
		<property name="strict_class_file_names" value="false"/>
	</properties>
</rule>

back to top

Custom word delimiters in hook names

WordPress Sniff Property name Property type Available since:
NamingConventions.ValidHookName additionalWordDelimiters string 0.10.0

The WordPress PHP Coding Standards Handbook states:

Use lowercase letters in action and filter names. Separate words via underscores.

Words in hook names should only be separated by underscores _. However, historically, in WordPress Core dashes - were used as well. Similarly there are well-known WordPress plugins and themes which use a different word separator in hook names.

The WordPress.NamingConventions.ValidHookName sniff will - by default - only allow an underscore as a word separator. However, the additionalWordDelimiters property allows you to add one or more extra allowed word delimiters.

Each character passed to the property will be treated as an extra allowed word delimiter.

<!-- Add one extra word delimiter. -->
<rule ref="WordPress.NamingConventions.ValidHookName">
	<properties>
		<property name="additionalWordDelimiters" value="-"/>
	</properties>
</rule>

<!-- Add several extra word delimiters. -->
<rule ref="WordPress.NamingConventions.ValidHookName">
	<properties>
		<property name="additionalWordDelimiters" value="-/."/>
	</properties>
</rule>

back to top

Mixed case property name exceptions

WordPress Sniff Property name Property type Available since:
NamingConventions.ValidVariableName customPropertiesWhitelist array 0.11.0

The WordPress PHP Coding Standards Handbook states:

Use lowercase letters in variable names.

Variable and class property names should be lowercase. The WordPress.NamingConventions.ValidVariableName sniff will take known exceptions, such as PHP reserved variables and WordPress core variables and properties which were inconsistently named, into account.

Still, if an application, for instance, uses external code modules and extends a PHP class from one of these modules which doesn't use snakecase property names, it may be unavoidable to use a certain mixed case class property.

This sniff property allows you to declare a whitelist of mixed case class property names used in your application. The mixed case property names on the whitelist will subsequently be disregarded by this sniff.

<rule ref="WordPress.NamingConventions.ValidVariableName">
	<properties>
		<property name="customPropertiesWhitelist" type="array">
			<element value="myMixedCasePropery"/>
			<element value="AnotherMixedCaseProperty"/>
		</property>
	</properties>
</rule>

back to top

CronInterval: minimum interval

WordPress Sniff Property name Property type Default: Available since:
WP.CronInterval min_interval int 900 0.14.0

The WordPress.WP.CronInterval sniff warns about cron schedules being added with a repeat frequency of less than 15 minutes (900 seconds).

The min_interval property allows for setting an arbitrary minimum interval value. The value has to be passed in seconds.

<rule ref="WordPress.WP.CronInterval">
	<properties>
		<property name="min_interval" value="1800"/>
	</properties>
</rule>

back to top

WP PostsPerPage: post limit

WordPress Sniff Property name Property type Default: Available since:
WP.PostsPerPage posts_per_page int 100 0.14.0

The WordPress.WP.PostsPerPage sniff warns about queries using a high pagination limit. By default "high" is interpreted as "more than 100 posts".

The posts_per_page property allows for setting an arbitrary limit.

<rule ref="WordPress.WP.PostsPerPage">
	<properties>
		<property name="posts_per_page" value="200"/>
	</properties>
</rule>

back to top

Custom database query caching functions

WordPress Sniff Property name Property type Available since:
DB.DirectDatabaseQuery customCacheGetFunctions array 0.6.0
DB.DirectDatabaseQuery customCacheSetFunctions array 0.6.0
DB.DirectDatabaseQuery customCacheDeleteFunctions array 0.6.0

The WordPress.DB.DirectDatabaseQuery sniff checks any queries made to the database use cachable WP functions to prevent unnecessarily querying the database multiple times for the same query.

Your application might have wrapper functions in place which handle the caching of database queries either via the WP native functions or via your own caching mechanism.

The above properties allow you to add the names of these functions to the list of functions which get/set/delete & cache database queries.

<rule ref="WordPress.DB.DirectDatabaseQuery">
	<properties>
		<property name="customCacheGetFunctions" type="array">
			<element value="prefix_get_from_db_and_cache"/>
			<element value="prefix_also_get_from_db_and_cache"/>
		</property>
		<property name="customCacheSetFunctions" type="array">
			<element value="prefix_get_from_db_and_cache"/>
		</property>
		<property name="customCacheDeleteFunctions" type="array">
			<element value="prefix_remove_from_db_cache"/>
		</property>
	</properties>
</rule>

back to top

Custom input sanitization functions

WordPress Sniff Property name Property type Available since:
Security.ValidatedSanitizedInput customSanitizingFunctions array 0.5.0
Security.ValidatedSanitizedInput customUnslashingSanitizingFunctions array 0.5.0
Security.NonceVerification customSanitizingFunctions array 0.11.0
Security.NonceVerification customUnslashingSanitizingFunctions array 0.11.0

The WordPress.Security.ValidatedSanitizedInput sniff checks that input variables ($_GET / $_POST) are unslashed and sanitized before use. The same checks are executed specifically for the nonce input variable in the WordPress.Security.NonceVerification sniff.

To do so, all safe PHP and WP core unslashing and sanitization functions are whitelisted.

Your application might have wrapper functions in place which handle the unslashing and sanitization of user input either via the WP native functions or via other means.

The above properties allow you to add the names of these functions to the whitelist of functions which unslash/sanitize user input.

It is recommended that you use the same function lists for both properties for all sniffs which support these properties.

<rule ref="WordPress.Security.ValidatedSanitizedInput">
	<properties>
		<property name="customSanitizingFunctions" type="array">
			<element value="prefix_sanitize_url"/>
			<element value="prefix_sanitize_postal_code"/>
		</property>
		<property name="customUnslashingSanitizingFunctions" type="array">
			<element value="prefix_sanitize_unslash_url"/>
		</property>
	</properties>
</rule>

<rule ref="WordPress.Security.NonceVerification">
	<properties>
		<property name="customSanitizingFunctions" type="array">
			<element value="prefix_sanitize_url"/>
			<element value="prefix_sanitize_postal_code"/>
		</property>
		<property name="customUnslashingSanitizingFunctions" type="array">
			<element value="prefix_sanitize_unslash_url"/>
		</property>
	</properties>
</rule>

back to top

Input validation scope

WordPress Sniff Property name Property type Default: Available since:
Security.ValidatedSanitizedInput check_validation_in_scope_only bool false 0.3.0

The WordPress.Security.ValidatedSanitizedInput sniff checks that input variables ($_GET / $_POST) are validated before use. "Validated" in this context means that it should be verified that the input variable exists via isset() or empty() before using it.

The check_validation_in_scope_only variable allows for tweaking of where the sniff looks for this validation.

// When `check_validation_in_scope_only` is `false`, this is considered valid:
if ( ! isset( $_GET['post_id'] ) ) {
	// Do stuff, like maybe return or exit (but could be anything)
}

foo( $_GET['post_id'] );

// When `check_validation_in_scope_only` is `true`, the above would be invalid.
// In that case, the variable will only be considered validated if used within
// the scope of the validating condition, like this:
if ( isset( $var ) ) {
	foo( $var );
}

By default, the property is set to false. You can change this in your ruleset to true if you want to limit the use of input variables to be within scoped validation conditions only.

<rule ref="WordPress.Security.ValidatedSanitizedInput">
	<properties>
		<property name="check_validation_in_scope_only" value="true"/>
	</properties>
</rule>

back to top

XSS: Custom output escaping functions

WordPress Sniff Property name Property type Available since:
Security.EscapeOutput customEscapingFunctions array 0.5.0 (0.3.0)
Security.EscapeOutput customAutoEscapedFunctions array 0.3.0

The WordPress.Security.EscapeOutput sniff checks that all output is escaped. To do so, all safe PHP and WP core functions which safely escape data are whitelisted.

Your application might have wrapper functions in place which handle the output escaping of data either via the WP native functions or via other means.

The above properties allow you to add the names of these functions to the whitelist of functions which either escape output (customEscapingFunctions) or the whitelist of functions which return pre-escaped data (customAutoEscapedFunctions).

<rule ref="WordPress.Security.EscapeOutput">
	<properties>
		<property name="customEscapingFunctions" type="array">
			<element value="prefix_escape_form_value"/>
			<element value="prefix_escape_form_id"/>
		</property>
		<property name="customAutoEscapedFunctions" type="array">
			<element value="prefix_get_escaped_value"/>
		</property>
	</properties>
</rule>

back to top

XSS: Custom printing functions

WordPress Sniff Property name Property type Available since:
Security.EscapeOutput customPrintingFunctions array 0.4.0

The WordPress.Security.EscapeOutput sniff checks that all output is escaped. To do so, the usage of all PHP and WP core functions and PHP language constructs which generate output - such as echo, print(), _e(), wp_die() - is checked.

Your application might have dedicated functions in place which generate output. If you want to enforce the WordPress.Security.EscapeOutput sniff for data passed to these functions, you will need to add them to the list of functions which will be checked.

To do so, pass the names of your custom printing functions to the sniff via your ruleset.

<rule ref="WordPress.Security.EscapeOutput">
	<properties>
		<property name="customPrintingFunctions" type="array">
			<element value="prefix_print_form_select_box"/>
			<element value="print_form_text_field"/>
		</property>
	</properties>
</rule>

back to top

CSRF: Custom nonce verification functions

WordPress Sniff Property name Property type Available since:
Security.NonceVerification customNonceVerificationFunctions array 0.5.0

The WordPress.Security.NonceVerification sniff checks that a nonce verification call is made before any - non-nonce - input variables ($_POST / $_FILE / $_GET / $_REQUEST) are used.

To do so, WP core functions which verify a nonce are whitelisted.

If you are unclear about why you should use nonces, please refer to the Codex.

Your application might have wrapper functions in place which handle the nonce verification either via the WP native functions or via other means.

The above property allows you to add the names of these functions to the whitelist of nonce verification functions.

<rule ref="WordPress.Security.NonceVerification">
	<properties>
		<property name="customNonceVerificationFunctions" type="array">
			<element value="prefix_verify_nonce"/>
		</property>
	</properties>
</rule>

back to top

Control structures: whitespace checking for closures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing spaces_before_closure_open_paren int -1 0.7.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check whether there is a space between the function keyword and the open parenthesis for closures.

This check is turned off by default.

To turn it on, set the spaces_before_closure_open_paren property to either 0 (space forbidden: function() {} ) or 1 (space required: function () {}).

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="spaces_before_closure_open_paren" value="0"/>
	</properties>
</rule>

back to top

Control structures: blank lines at the start and end of control structures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing blank_line_check bool false 0.2.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check for stray blank lines at the start and end of control structures and to remove these with the fixer.

This check is turned off by default. To turn it on, set the blank_line_check property to true.

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="blank_line_check" value="true"/>
	</properties>
</rule>

back to top

Control structures: blank lines after control structures

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing blank_line_after_check bool true 0.3.0

The WordPress.WhiteSpace.ControlStructureSpacing sniff has the ability to check for stray blank lines after control structures and to removed these with the fixer.

This check is turned on by default. To turn it off, set the blank_line_after_check property to false.

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="blank_line_after_check" value="false"/>
	</properties>
</rule>

back to top

Control structures: space before colon in alternative syntax

WordPress Sniff Property name Property type Default: Available since:
WhiteSpace.ControlStructureSpacing space_before_colon string required 0.4.0

For control structures using alternative syntax - as often used in themes - the WordPress.WhiteSpace.ControlStructureSpacing sniff checks for a space between the condition and the colon.

// Good:
<php if ( isset( $foo ) ) : ?>
Foo!
<?php endif; ?>
// Bad:
<php if ( isset( $foo ) ): ?>
Foo!
<?php endif; ?>

This space is required by default.

You can change this requirement by setting the space_before_colon property. Allowed values: required, forbidden (space not allowed), optional (check is skipped).

<rule ref="WordPress.WhiteSpace.ControlStructureSpacing">
	<properties>
		<property name="space_before_colon" value="forbidden"/>
	</properties>
</rule>

back to top

Precision alignment: exempt certain tokens

WordPress Sniff Property name Property type Available since:
WhiteSpace.PrecisionAlignment ignoreAlignmentTokens array 0.14.0

The WordPress.WhiteSpace.PrecisionAlignment sniff detects precision alignment, i.e. indentation to a position not equal to a tab-stop.

Precision alignment is rarely needed and discouraged for WordPress Core.

The ignoreAlignmentTokens property allows for providing a list of tokens for which (preceding) precision alignment should be ignored.

<rule ref="WordPress.WhiteSpace.PrecisionAlignment">
	<properties>
		<property name="ignoreAlignmentTokens" type="array">
			<element value="T_COMMENT"/>
			<element value="T_INLINE_HTML"/>
		</property>
	</properties>
</rule>

back to top

Arrays: Forcing single item associative arrays to be multi-line

WordPress Sniff Property name Property type Default: Available since:
Arrays.ArrayDeclarationSpacing allow_single_item_single_line_associative_arrays bool true 0.14.0

Since WPCS 0.11.0, the WordPress.Arrays.ArrayDeclarationSpacing sniff contained a check that any associative array was multi-line. In August 2017, the WP Core handbook has been adjusted to only demand this for multi-item associative arrays and the sniff has been adjusted accordingly. This change is included in WPCS since version 0.14.0.

By setting the allow_single_item_single_line_associative_arrays property to false, the sniff will revert to its original behaviour and continue to demand multi-line formatting for all associative arrays, independently of the number of array items.

<rule ref="WordPress.Arrays.ArrayDeclarationSpacing">
	<properties>
		<property name="allow_single_item_single_line_associative_arrays" value="false"/>
	</properties>
</rule>

back to top

Array alignment: allow for new lines

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment ignoreNewlines bool true 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

To avoid excessively long lines, sometimes the array assignment operator will be on a new line:

$array = array(
    'really_long_array_key'
        => 'an even longer value........................................................',
);

By default this style of array definition is allowed.

By setting the ignoreNewlines property to false, you can force the sniff to throw errors for this and to auto-fix this when running phpcbf.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="ignoreNewlines" value="false"/>
	</properties>
</rule>

back to top

Array alignment: allow non-exact alignment

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment exact bool true 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

If the exact property is true (default), the alignment has to be exactly 1 space from the end of the widest index.

By setting the exact property to false, this behaviour can be made more lenient.

When set to false, the largest index key + 1 space is taken as a minimum and if a predominant number of items is already aligned at a position which is more than the minimum, this predominant alignment position is taken as the preferred alignment.

This allows for cleaner diffs as the array operators do not have to be realigned when the array item with the largest key is taken out.

Example:

/*
 * With `exact` set to `true`, this array would be fixed to align at the end
 * of `even_longer_key` + 1 space.
 * With `exact` set to `false`, the below would be accepted as a valid alignment.
 *
 * And with `exact` set to `false`, taking the `even_longer_key` array item
 * out of the array would not impact the alignment, while with `exact` set
 * to `true`, the assignment operators for the whole array would need
 * to be re-aligned.
 */
$array = array(
    'short_key'         => 'value',
    'longer_key'        => 'value',
    'even_longer_key'   => 'value',
);
<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="exact" value="false"/>
	</properties>
</rule>

back to top

Array alignment: maximum column

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment maxColumn int 1000 0.14.0

Note: while the sniff default is 1000, the WordPress-Core setting for this property is 60!

As the WordPress-Core ruleset is included in the WordPress and WordPress-Extra rulesets, this value of 60 will be inherited by these two rulesets.

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

When an array contains very long keys or has a lot or indentation/nesting, this alignment could make the lines even longer.

To avoid excessively long lines, the maximum position within a line at which an array assignment operator will be aligned is determined by the maxColumn property.

For example, if this value is set to 60, as it is for the WordPress-Core ruleset, it will:

  • if the expected column < 60, align at the expected column.
  • if the expected column >= 60, align at column 60.
  • for the outliers, i.e. the array indexes where the end position goes past column 60, it will not align the arrow, the sniff will just make sure there is only one space between the end of the array index and the double arrow.

N.B.: The maxColumn value is regarded as a hard value, i.e. includes indentation, so setting it very low is not a good idea.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="maxColumn" value="80"/>
	</properties>
</rule>

back to top

Array alignment: dealing with multi-line items

WordPress Sniff Property name Property type Default: Available since:
Arrays.MultipleStatementAlignment alignMultilineItems string always 0.14.0

The WordPress.Arrays.MultipleStatementAlignment sniff verifies that all array assignment operators, i.e. the double arrows - => -, in a multi-line, multi-statement array are aligned.

Sometimes, however, there may be complex nested arrays which makes alignment of the top-level array assignment operators awkward.

With this property, you can toggle whether or not to align the arrow operator for multi-line array items, such as array items with another array as the value.

Note: Whether or not an item is regarded as multi-line is based on the value of the item, not the key.

Valid values for the property are:

  • always: Default. Align all arrays items regardless of single/multi-line.

  • never: Never align array items which span multiple lines.

    This will enforce one space between the array index and the double arrow operator for multi-line array items, independently of the alignment of the rest of the array items.

    Multi-line items where the arrow is already aligned with the "expected" alignment, however, will be left alone.

  • operator + number : Only align the operator for multi-line arrays items if the percentage of multi-line items passes the comparison.

    • As it is a percentage, the number has to be between 0 and 100.
    • Supported operators: <, <=, >, >=, ==, =, !=, <>
    • The percentage is calculated against all array items (with and without assignment operator).
    • The (new) expected alignment will be calculated based only on the items being aligned.
    • Multi-line items where the arrow is already aligned with the (new) "expected" alignment, however, will be left alone.

    Examples:

    • Setting this to !=100 or <100 means that alignment will be enforced, unless all array items are multi-line.

      This is probably the most commonly desired situation.

    • Setting this to =100 means that alignment will only be enforced, if all array items are multi-line.

    • Setting this to <50 means that the majority of array items need to be single line before alignment is enforced for multi-line items in the array.

    • Setting this to =0 is useless as in that case there are no multi-line items in the array anyway.

This setting will respect the ignoreNewlines and maxColumnn settings.

<rule ref="WordPress.Arrays.MultipleStatementAlignment">
	<properties>
		<property name="alignMultilineItems" value="!=100"/>
	</properties>
</rule>

back to top

Error silencing: context code snippet length

WordPress Sniff Property name Property type Default: Available since:
PHP.NoSilencedErrors context_length int 6 1.1.0

The WordPress.PHP.NoSilencedErrors sniff detects usage of the PHP error control operator @.

The warning message from this sniff, displays a short snippet of code to provide a clue to the context in which the use of the error control operator was detected.

The context_length property allows customizing the length (in tokens) of the code snippet to be displayed.

<rule ref="WordPress.PHP.NoSilencedErrors">
	<properties>
		<property name="context_length" value="8"/>
	</properties>
</rule>

back to top

Error silencing: use build-in function whitelist

WordPress Sniff Property name Property type Default: Available since:
PHP.NoSilencedErrors use_default_whitelist bool true 1.1.0

The WordPress PHP Coding Standards Handbook states:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

While this operator does exist in Core, it is often used lazily instead of doing proper error checking. Its use is highly discouraged.

The WordPress.PHP.NoSilencedErrors sniff detects usage of the PHP error control operator @.

In rare cases, no amount of error checking can prevent PHP errors from being thrown and the use of the error control operator could be considered legitimate.

The WordPress.PHP.NoSilencedErrors sniff comes with a default whitelist of a limited set of native PHP functions for which this applies.

While the warnings these functions throw are legitimate and should be allowed to be logged, a case can also be made that these should be silenced for end-users who have no clue how to handle these type of warnings.

The use_default_whitelist property determines whether the build-in whitelist should be used by the sniff or not.

For the WordPress-Core ruleset, this property is set to the default, true.

For the WordPress-Extra ruleset, this property is set to false, i.e. the error control operator should not be used at all.

<rule ref="WordPress.PHP.NoSilencedErrors">
	<properties>
		<property name="use_default_whitelist" value="true"/>
	</properties>
</rule>

back to top

Error silencing: custom function whitelist

WordPress Sniff Property name Property type Available since:
PHP.NoSilencedErrors custom_whitelist array 1.1.0

The WordPress PHP Coding Standards Handbook states:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

While this operator does exist in Core, it is often used lazily instead of doing proper error checking. Its use is highly discouraged.

The WordPress.PHP.NoSilencedErrors sniff detects usage of the PHP error control operator @.

The custom_whitelist property allows for providing a list of function names, for which - when the error control operator is detected as being used for that function - no warning will be thrown.

<rule ref="WordPress.PHP.NoSilencedErrors">
	<properties>
		<property name="custom_whitelist" type="array">
			<element value="unlink"/>
			<element value="preg_match"/>
		</property>
	</properties>
</rule>

back to top

Optional, but discouraged properties

Global WP Variable Override: check in the global namespace

WordPress Sniff Property name Property type Default: Available since:
WP.GlobalVariablesOverride treat_files_as_scoped bool false 1.1.0

The WordPress.WP.GlobalVariablesOverride sniff checks if WordPress variables declared in the global namespace are being overridden by plugins or themes - which is bad practice as it makes them unreliable for other plugins/themes as well as for WP itself.

Sometimes files - most notably views - are included from within a function in another file, making all variable declarations within the view file local to that function. In that case, this sniff is likely to throw false positives - since WPCS 1.1.0 -.

Prior to WPCS 1.1.0, the sniff would only check variables within the global namespace of a file when a global statement referencing the variable would be encountered.

While including the view from within a function may be the common usecase for such a file, there is no guarantee that the view file will always be included from within a function, so using variable names which intersect with the WP global variables should still be considered bad practice.

To revert to the pre-WPCS 1.1.0 sniff behaviour, the treat_files_as_scoped property can be set to true.

Unfortunately, at this time, it is not possible to set this property for only a select group of files. With that in mind, setting this property is discouraged.

<rule ref="WordPress.WP.GlobalVariablesOverride">
	<properties>
		<property name="treat_files_as_scoped" value="true"/>
	</properties>
</rule>

back to top

Internationalization: check for translators comments

WordPress Sniff Property name Property type Default: Available since:
WP.I18n check_translator_comments bool true 0.11.0

Allows to turn off checking for translators comments for text strings containing placeholders.

<rule ref="WordPress.WP.I18n">
	<properties>
		<property name="check_translator_comments" value="false"/>
	</properties>
</rule>

Note: Alternatively, you can achieve the same effect by using the following syntax in your custom ruleset:

<rule ref="WordPress">
	<exclude name="WordPress.WP.I18n.TranslatorsCommentWrongStyle"/>
	<exclude name="WordPress.WP.I18n.MissingTranslatorsComment"/>
</rule>

back to top