Skip to content

Customizable sniff properties

Janw Oostendorp edited this page Sep 17, 2023 · 56 revisions

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 WordPressCS 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 WordPressCS. 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. WordPressCS 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 WordPressCS 1.0.0 and as of WordPressCS 2.0, support for incorrectly passed array properties has been removed.

WordPressCS also uses a number of upstream sniffs.

  • For a list of customizable sniff properties for the PHP_CodeSniffer native sniffs - sniffs starting with Generic, PEAR, PSR1, PSR2, PSR12, Squiz or Zend -, please see the PHPCS Customisable Sniff Properties wiki page.
  • For a list of customizable sniff properties for the PHPCSExtra sniffs - sniffs starting with Modernize, NormalizedArrays or Universal -, please see the PHPCSExtra README.

Table of contents

Properties strongly recommended to be set

WordPress.WP.I18n: setting your text domain

Property name Type Available since:
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 (WordPressCS 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

WordPress.NamingConventions.PrefixAllGlobals: prefix everything in the global namespace

Property name Type Available since:
prefixes array 0.12.0

Prefixing all functions, namespaces, classes, interfaces, traits, enums, 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

Various sniffs: set the minimum supported WP version

WordPress Sniff Property name Type Available since:
DB.PreparedSQLPlaceholders minimum_wp_version string 3.0.0
WP.AlternativeFunctions minimum_wp_version string 1.0.0
WP.Capabilities minimum_wp_version string 3.0.0
WP.DeprecatedClasses minimum_wp_version string 0.12.0
WP.DeprecatedFunctions minimum_wp_version string 0.11.0
WP.DeprecatedParameters minimum_wp_version string 0.12.0
WP.DeprecatedParameterValues minimum_wp_version string 1.0.0

👉 Prior to WordPressCS 3.0.0, the property name used was minimum_supported_version.

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

For deprecations before the minimum_wp_version, these will throw an error. For deprecations between the minimum_wp_version and the current release (inclusive), these 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_wp_version is 4.6 or higher. It will throw a warning if the minimum_wp_version is 4.5 or lower.

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

The WordPress.DB.PreparedSQLPlaceholders sniff uses the property to check whether the %i placeholder can be used.

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

For example: at the time of writing, the latest released WP version is 6.3.0, so the default value of the minimum_wp_version property is currently 6.0.

<rule ref="WordPress.WP.DeprecatedFunctions">
	<properties>
		<property name="minimum_wp_version" value="5.2"/>
	</properties>
</rule>

Setting minimum supported WP version for all sniffs in one go (WordPressCS 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_wp_version" value="4.5"/>

👉 Prior to WordPressCS 3.0.0, this config directive was called minimum_supported_wp_version.

Setting minimum supported WP version from the command line (WordPressCS 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_wp_version and pass the version number.

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

👉 Prior to WordPressCS 3.0.0, the setting name for CLI was called minimum_supported_wp_version.

back to top

WordPress.Files.FileName: allow filename exceptions for themes

Property name Type Default: Available since:
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 are 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

WordPress.WP.Capabilities: ensure recognition of custom capabilities

Property name Type Available since:
custom_capabilities array 3.0.0

The WordPress.WP.Capabilities sniff will verify that capabilities are used correctly. User capabilities should be used, not roles or deprecated capabilities.

By default, unknown capabilities will be flagged by the sniff.

To ensure the sniff does not flag the use of custom capabilities registered by your plugin/theme, you can make those known to WordPressCS.

<rule ref="WordPress.WP.Capabilities">
	<properties>
		<property name="custom_capabilities" type="array">
			<element value="my_post_type_read"/>
			<element value="my_post_type_admin"/>
		</property>
	</properties>
</rule>

back to top

Various sniffs: custom unit test classes

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

👉 Prior to WordPressCS 3.0.0, this property was called custom_test_class_whitelist.

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 ignored for those specific checks.

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

  • Global Variable overrides in test classes: Sometimes WordPress global variables will need to be overloaded in unit test situations. The sniff allows for this.
  • File name rules do not apply to test classes. Files containing test classes should follow the naming conventions as expected by the test framework used; 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 in the context of WordPress, there is no risk of naming collisions.

You may be using a custom unit test base class in your WordPress application.

The custom_test_classes property allows you to declare 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_classes" type="array">
			<element value="My_Unit_TestCase"/>
			<element value="My\Plugin\Integrations\TestCase"/>
		</property>
	</properties>
</rule>

Note that custom test case classes that aren't named TestCase or which are imported via a use statement are not considered. The following two examples will not work:

use My\Plugin\Integrations\MyTestCase;

class MySpecificTest extends MyTestCase {
namespace Foo;
use My\Plugin\Integrations\TestCase;

class MySpecificTest extends TestCase {

Instead, you'll need to do the following:

class MySpecificTest extends My\Plugin\Integrations\TestCase {

Pro-tip: Instead of using the property, use an <exclude-pattern> for the project's tests directory/directories for each of these sniffs. For example:

<rule ref="WordPress.Files.FileName">
	<exclude-pattern>tests/</exclude-pattern>
</rule>

back to top

Optional properties

Various sniffs: excluding a group of checks

WordPress Sniff Property name Type Available since: Groups:
DateTime.RestrictedFunctions exclude array 2.2.0 timezone_change, date
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, unlink, rename, file_system_operations (was called file_system_read prior to 3.0.0), strip_tags (since 1.0.0), rand_seeding (since 1.0.0), rand (since 1.0.0)
WP.ClassNameCase exclude array 3.0.0 wp_classes, wp_themes_classes, getid3_classes, phpmailer_classes, requests_classes, simplepie_classes
WP.DiscouragedFunctions exclude array 0.11.0 query_posts, wp_reset_query
WP.PostsPerPage exclude array 1.0.0 posts_per_page
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.
WP.TimezoneChange exclude array 0.11.0 timezone_change This sniff has been removed as of WordPressCS 3.0.0

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

WordPress.Files.FileName: disregard class file name rules

Property name Type Default: Available since:
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 WordPress 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

WordPress.NamingConventions.ValidHookName: custom word delimiters in hook names

Property name Type Available since:
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

WordPress.NamingConventions.ValidVariableName: mixed case property name exceptions

Property name Type Available since:
allowed_custom_properties array 0.11.0

👉 Prior to WordPressCS 3.0.0, this property was called customPropertiesWhitelist.

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 list of known mixed case class property names used in your application. The mixed case property names on this list will subsequently be disregarded by this sniff.

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

back to top

WordPress.WP.CronInterval: minimum interval

Property name Type Default: Available since:
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

WordPress.WP.PostsPerPage: customizing the post limit

Property name Type Default: Available since:
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

WordPress.DB.DirectDatabaseQuery: custom database query caching functions

Property name Type Available since:
customCacheGetFunctions array 0.6.0
customCacheSetFunctions array 0.6.0
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

WordPress.Security.NonceVerification/ValidatedSanitizedInput: custom input sanitization functions

WordPress Sniff Property name 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 WordPress core unslashing and sanitization functions are taken into account.

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 lists of known 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

WordPress.Security.ValidatedSanitizedInput: input validation scope

Property name Type Default: Available since:
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

WordPress.Security.EscapeOutput: custom output escaping functions

Property name Type Available since:
customEscapingFunctions array 0.5.0 (0.3.0)
customAutoEscapedFunctions array 0.3.0

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

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

The above properties allow you to add the names of these functions to the list of known functions which escape output (customEscapingFunctions) or to the list of known 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"/>
			<element value="\QualifiedExample\Namespaced\ClassName::staticMethod"/>
		</property>
		<property name="customAutoEscapedFunctions" type="array">
			<element value="prefix_get_escaped_value"/>
		</property>
	</properties>
</rule>

back to top

WordPress.Security.EscapeOutput: custom printing functions

Property name Type Available since:
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 WordPress 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

WordPress.Security.NonceVerification: custom nonce verification functions

Property name Type Available since:
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, the sniff searches for a function call to known WordPress core functions which verify a nonce.

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

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

The above property allows you to add the names of these functions to the list of known 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

WordPress.WhiteSpace.ControlStructureSpacing: blank lines at the start and end of control structures

Property name Type Default: Available since:
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

WordPress.WhiteSpace.ControlStructureSpacing: blank lines after control structures

Property name Type Default: Available since:
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

WordPress.WhiteSpace.ControlStructureSpacing: space before colon in alternative syntax

Property name Type Default: Available since:
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

WordPress.Arrays.ArrayDeclarationSpacing: forcing single item associative arrays to be multi-line

Property name Type Default: Available since:
allow_single_item_single_line_associative_arrays bool true 0.14.0

Since WordPressCS 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 WordPressCS 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

WordPress.Arrays.MultipleStatementAlignment: allow for new lines

Property name Type Default: Available since:
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

WordPress.Arrays.MultipleStatementAlignment: allow non-exact alignment

Property name Type Default: Available since:
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

WordPress.Arrays.MultipleStatementAlignment: maximum column

Property name Type Default: Available since:
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

WordPress.Arrays.MultipleStatementAlignment: dealing with multi-line items

Property name Type Default: Available since:
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

WordPress.PHP.NoSilencedErrors: context code snippet length

Property name Type Default: Available since:
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

WordPress.PHP.NoSilencedErrors: use build-in functions list

Property name Type Default: Available since:
usePHPFunctionsList bool true 1.1.0

👉 Prior to WordPressCS 3.0.0, this property was called use_default_whitelist.

The WordPress PHP Coding Standards Handbook states:

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

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 list of a limited set of known 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 usePHPFunctionsList property determines whether the build-in list of known functions 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="usePHPFunctionsList" value="true"/>
	</properties>
</rule>

back to top

WordPress.PHP.NoSilencedErrors: custom allowed functions list

Property name Type Available since:
customAllowedFunctionsList array 1.1.0

👉 Prior to WordPressCS 3.0.0, this property was called custom_whitelist.

The WordPress PHP Coding Standards Handbook states:

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

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 customAllowedFunctionsList 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="customAllowedFunctionsList" type="array">
			<element value="unlink"/>
			<element value="preg_match"/>
		</property>
	</properties>
</rule>

back to top

WordPress.Utils.I18nTextDomainFixer: replace a text_domain

Property name Type Available since:
old_text_domain array 1.2.0
new_text_domain string 1.2.0

The WordPress.Utils.I18nTextDomainFixer sniff can replace the text domain used in a code-base.

The sniff can fix the text domains in both I18n function calls as well as in a plugin/theme header.

To activate the sniff, both properties need to be set.

Set old_text_domain to an array with one or more (old) text domain names which need to be replaced. Set new_text_domain to the correct (new) text domain as a string.

<rule ref="WordPress.Utils.I18nTextDomainFixer">
	<properties>
		<property name="old_text_domain" type="array">
			<element value="old_domain_A"/>
			<element value="old_domain_B"/>
		</property>
		<property name="new_text_domain" value="new_domain"/>
	</properties>
</rule>

back to top

Optional, but discouraged properties

WordPress.WP.GlobalVariablesOverride: check in the global namespace

Property name Type Default: Available since:
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 WordPress 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 WordPressCS 1.1.0 -.

Prior to WordPressCS 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 WordPress global variables should still be considered bad practice.

To revert to the pre-WordPressCS 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

Removed properties

Historical reference of removed properties

WordPress.WhiteSpace.ControlStructureSpacing: whitespace checking for closures

❌ This property has been removed in WordPressCS 3.0.0. Closures will now always be enforced to have 1 space between the function keyword and the open parentheses.

Property name Type Default: Available since: Removed:
spaces_before_closure_open_paren int -1 0.7.0 3.0.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

WordPress.WhiteSpace.PrecisionAlignment: exempt certain tokens

❌ This sniff has been replaced in WordPressCS 3.0.0 by the Universal.Whitespace.PrecisionAlignment sniff.

Property name Type Available since: Removed:
ignoreAlignmentTokens array 0.14.0 3.0.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

WordPress.WP.I18n: check for translators comments

❌ This property has been removed in WordPressCS 3.0.0.

Property name Type Default: Available since: Removed:
check_translator_comments bool true 0.11.0 3.0.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

Clone this wiki locally