### Markdown Tables Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Provides an example of Markdown syntax for creating tables, using pipes and hyphens to define columns and rows. ```markdown | A | B | | ----- | ----- | | Alpha | Bravo | ``` -------------------------------- ### Documenting Required/Included PHP Files Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This example shows the DocBlock format for documenting files that are required or included in PHP. It requires a summary description for the file. ```php /** * Summary. */ require_once( ABSPATH . WPINC . '/filename.php' ); ``` -------------------------------- ### Markdown Fenced Code Blocks (Markdown) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Example of Markdown syntax itself presented within a Markdown fenced code block, useful for documenting Markdown examples. ```markdown This is _italic text_. This is **bold text**. ``` -------------------------------- ### PHP DocBlock: Code Sample Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Shows how to embed a code sample within a PHP DocBlock description. Each line of the code, including blank lines, must be indented by four spaces. ```php * Description including a code sample: * * $status = array( * 'draft' => __( 'Draft' ), * 'pending' => __( 'Pending Review' ), * 'private' => __( 'Private' ), * 'publish' => __( 'Published' ) * ); * * The description continues on ... ``` -------------------------------- ### JavaScript Switch Statement Examples Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md Provides examples of using `switch` statements in JavaScript, including handling multiple cases with the same block and fall-through logic. It also shows a recommended pattern for returning values from a switch statement by assigning to a variable within the `case` blocks and returning at the end. ```javascript switch ( event.keyCode ) { // ENTER and SPACE both trigger x() case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: x(); break; case $.ui.keyCode.ESCAPE: y(); break; default: z(); } ``` ```javascript function getKeyCode( keyCode ) { var result; switch ( event.keyCode ) { case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: result = 'commit'; break; case $.ui.keyCode.ESCAPE: result = 'exit'; break; default: result = 'default'; } return result; } ``` -------------------------------- ### Markdown Strikethrough Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Illustrates how to apply strikethrough formatting to text by wrapping it with double tildes. ```markdown This is ~~strikethrough~~ text. ``` -------------------------------- ### PHP DocBlock: Unordered List Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Demonstrates how to include an unordered list within a PHP DocBlock description using hyphens. A blank line is required before and after the list. ```php * Description which includes an unordered list: * * - This is item 1. * - This is item 2. * - This is item 3. * * The description continues on ... ``` -------------------------------- ### PHP DocBlock: Ordered List Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Illustrates the correct way to format an ordered list within a PHP DocBlock description using numbers. Ensure blank lines precede and follow the list. ```php * Description which includes an ordered list: * * 1. This is item 1. * 2. This is item 2. * 3. This is item 3. * * The description continues on ... ``` -------------------------------- ### PHP DocBlock: @since Tag Basic Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Demonstrates the basic usage of the `@since` tag in a PHP DocBlock to indicate the version the code was introduced. Versions should follow the x.x.x format. ```php * @since 4.4.0 ``` -------------------------------- ### Markdown Inline Code Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Illustrates how to format inline code snippets within Markdown text using single backticks. ```markdown This is `inline code` wrapped with backticks ``` -------------------------------- ### PHP DocBlock: @since Tag Changelog Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Illustrates how to use multiple `@since` tags in a PHP DocBlock to create a changelog for significant changes. Each entry includes the version and a description of the change. ```php * @since 3.0.0 * @since 3.8.0 Added the `post__in` argument. * @since 4.1.0 The `$force` parameter is now optional. ``` -------------------------------- ### PHP DocBlock: @link Tag Example Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Provides an example of using the `@link` tag in a PHP DocBlock to reference external resources like Trac tickets or documentation. The URL follows the tag. ```php * Description text. * * @link https://core.trac.wordpress.org/ticket/20000 ``` -------------------------------- ### Markdown Links Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Explains the syntax for creating hyperlinks in Markdown, requiring the link title in square brackets and the URL in parentheses. ```markdown [WordPress](https://wordpress.org/) ``` -------------------------------- ### Markdown Fenced Code Blocks (Javascript) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Example of a Javascript code block enclosed in Markdown fenced code syntax, specifying the language for syntax highlighting. ```javascript var foo = function (bar) { return bar++; }; console.log(foo(5)); ``` -------------------------------- ### Markdown Fenced Code Blocks (JSON) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Example of a JSON data structure formatted within a Markdown fenced code block, indicating the language as JSON. ```json { "firstName": "John", "lastName": "Smith", "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ], "children": [], "spouse": null } ``` -------------------------------- ### Single-line Inline Comments in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This example shows the standard format for single-line inline comments within PHP code, used for brief explanations of code functionality. ```php // Allow plugins to filter an array. ``` -------------------------------- ### Markdown Headings Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Demonstrates the use of Markdown for creating headings from h1 to h6. Headings h1 through h4 are automatically added to the Table of Contents. ```markdown # Heading h1 ## Heading h2 ### Heading h3 #### Heading h4 ##### Heading h5 ###### Heading h6 ``` -------------------------------- ### JavaScript Code Formatting Examples Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md Illustrates good spacing practices in JavaScript, including conditional statements, object literals, and loop structures. Highlights WordPress-specific preferences like spacing after the negation operator. ```javascript var i; if ( condition ) { doSomething( 'with a string' ); } else if ( otherCondition ) { otherThing( { key: value, otherKey: otherValue } ); } else { somethingElse( true ); } // Unlike jQuery, WordPress prefers a space after the ! negation operator. // This is also done to conform to our PHP standards. while ( ! condition ) { iterating++; } for ( i = 0; i < 100; i++ ) { object[ array[ i ] ] = someFn( i ); $( '.container' ).val( array[ i ] ); } try { // Expressions } catch ( e ) { // Expressions } ``` -------------------------------- ### PHP Multi-line Comments Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Demonstrates the correct way to format multi-line comments in PHP according to WordPress coding standards. Multi-line comments should start with a single asterisk `/*` and not a double asterisk `/**` to avoid being mistaken for DocBlocks. ```php /* * This is a comment that is long enough to warrant being stretched over * the span of multiple lines. You'll notice this follows basically * the same format as the PHPDoc wrapping and comment block style. */ ``` -------------------------------- ### Markdown Blockquotes Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Demonstrates the use of the greater-than symbol (>) for creating blockquotes, with double greater-than symbols (>>) for nested indentation. ```markdown > Blockquote >> Indented Blockquote ``` -------------------------------- ### Markdown Lists (Unordered and Ordered) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Covers the creation of both unordered lists using hyphens and ordered lists using numbered items followed by a period. Indentation is used for sub-items. ```markdown - List - List - List - List 1. One 2. Two 3. Three ``` -------------------------------- ### Markdown Fenced Code Blocks (CSS) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Demonstrates a CSS code snippet enclosed in Markdown fenced code syntax, with the language specified as CSS. ```css foo { padding: 5px; margin-right: 3px; } .bar { background-color: #f00; } ``` -------------------------------- ### Markdown Emphasis (Italics and Bold) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Shows how to format text in italics using single underscores and in bold using double asterisks. These are common text formatting techniques in Markdown. ```markdown This is _italic text_. This is **bold text**. ``` -------------------------------- ### Markdown Fenced Code Blocks (PHP) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Illustrates a PHP code snippet enclosed in Markdown fenced code syntax, with the language declared as PHP. ```php $array = array( "foo" => "bar", "bar" => "foo", ); ``` -------------------------------- ### CSS Property Ordering: Logical Grouping Example Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/css.md Demonstrates logical grouping of CSS properties for better organization. Properties are grouped by meaning (e.g., display, positioning, box model, colors, typography) and ordered strategically within groups to create smooth transitions. ```css #overlay { position: absolute; z-index: 1; padding: 10px; background: #fff; color: #777; } ``` -------------------------------- ### Markdown Fenced Code Blocks (HTML) Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Shows a basic HTML element formatted as a fenced code block in Markdown, specifying the language as HTML. ```html Example ``` -------------------------------- ### CSS Property Ordering: Alphabetical Example Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/css.md Presents an alternative method for ordering CSS properties alphabetically. This approach, sometimes used by the Automattic/WordPress.com Themes Team, aims for a different kind of consistency. ```css #overlay { background: #fff; color: #777; padding: 10px; position: absolute; z-index: 1; } ``` -------------------------------- ### Avoid Shorthand PHP Tags Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Always use full PHP start tags (``) and never shorthand PHP tags (`` or ``). This ensures consistency and avoids potential issues. ```php ``` ```php ``` -------------------------------- ### Incorrect Object Instantiation Syntax in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Highlights incorrect syntax for object instantiation in PHP, such as omitting parentheses when creating new instances or including a space between the class name and the opening parenthesis. These examples violate WordPress coding standards. ```php // Incorrect. $foo = new Foo; $anonymous_class = new class ( $input ) { ... }; ``` -------------------------------- ### JavaScript Comments: Standard and JSDoc Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md Demonstrates standard single-line and multi-line comments, as well as JSDoc-style comments for JavaScript. Comments should precede the code they describe, start with a capital letter, end with a period, and have a space after the comment token. JSDoc comments use `/**` for multi-line documentation. ```javascript someStatement(); // Explanation of something complex on the next line $( 'p' ).doSomething(); // This is a comment that is long enough to warrant being stretched // over the span of multiple lines. ``` ```javascript function foo( types, selector, data, fn, /* INTERNAL */ one ) { // Do stuff } ``` -------------------------------- ### Documenting Backbone.js Initialize Functions with JSDoc Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/javascript.md Demonstrates how to document Backbone.js `initialize` functions using JSDoc. It specifies the required tags for class definitions, deprecation, versioning, inheritance, and parameter documentation, including specific parameters for Models and Views. ```javascript Class = Parent.extend( /** @lends namespace.Class.prototype */{ /** * Summary. (use period) * * Description. (use period) * * @since x.x.x * @deprecated x.x.x Use new_function_name() instead. * @access private * * @constructs namespace.Class * @augments Parent * @mixes mixin * * @alias realName * @memberof namespace * * @see Function/class relied on * @link URL * @fires Class#eventName * * @param {Object} attributes The model's attributes. * @param {type} attributes.key One of the model's attributes. * @param {Object} [options] The model's options. * @param {type} options.key One of the model's options. */ initialize: function() { //Do stuff. } } ); ``` -------------------------------- ### Documenting PHP Classes with DocBlocks Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This snippet demonstrates the standard DocBlock format for documenting PHP classes in WordPress. It includes a summary, an optional detailed description, and the `@since` tag for versioning. For subclasses, an `@see` tag referencing the superclass is also recommended. ```php /** * Summary. * * Description. * * @since x.x.x */ ``` ```php /** * Summary. * * Description. * * @since x.x.x * * @see Super_Class */ ``` -------------------------------- ### JSHint via Grunt for WordPress JavaScript Source: https://context7.com/wordpress/wpcs-docs/llms.txt Guides on running JSHint through Grunt to validate JavaScript code against WordPress standards. It includes installing Node.js dependencies, running JSHint on core or test files, and targeting specific files. ```bash # Install Node.js dependencies (from WordPress root) npm install # Run JSHint on all core JavaScript files npm run grunt jshint # Check only core files npm run grunt jshint:core # Check only test files npm run grunt jshint:tests # Target a single file npm run grunt jshint:core --file=admin-bar.js ``` -------------------------------- ### Camel Case Naming for Variables and Functions in JavaScript Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md This example illustrates the camel case naming convention for variables and functions in JavaScript, where the first letter is lowercase and subsequent words start with an uppercase letter. It also shows exceptions for iterators like `i`. ```javascript // "Id" is an abbreviation of "Identifier": const userId = 1; // "DOM" is an acronym of "Document Object Model": const currentDOMDocument = window.document; // Acronyms and abbreviations at the start of a variable name are consistent // with camelcase rules covering the first letter of a variable or class. const domDocument = window.document; class DOMDocument {} class IdCollection {} ``` -------------------------------- ### Documenting PHP Action and Filter Hooks Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This snippet demonstrates the standard DocBlock format for documenting WordPress action and filter hooks. It includes a summary, an optional description, `@since` for versioning, and `@param` tags for hook arguments. The `@ignore` tag can be used for internal hooks. ```php /** * Summary. * * Description. * * @since x.x.x * * @param type $var Description. * @param array $args { * Short description about this hash. * * @type type $var Description. * @type type $var Description. * } * @param type $var Description. */ ``` -------------------------------- ### Documenting PHP Class Properties with DocBlocks Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This code shows how to document class properties using DocBlocks. It requires a summary, the `@since` tag for versioning, and the `@var` tag to specify the type and description of the property. ```php /** * Summary. * * @since x.x.x * @var type $var Description. */ ``` -------------------------------- ### PHP_CodeSniffer for WordPress PHP Code Source: https://context7.com/wordpress/wpcs-docs/llms.txt Instructions for installing and using PHP_CodeSniffer with WordPress Coding Standards (WPCS) to check and fix PHP code. It covers installation via Composer, configuration, checking files, and auto-fixing issues. ```bash # Install WordPress Coding Standards via Composer composer require --dev wp-coding-standards/wpcs # Configure phpcs to use WordPress standards ./vendor/bin/phpcs --config-set installed_paths vendor/wp-coding-standards/wpcs # Check a file against WordPress standards ./vendor/bin/phpcs --standard=WordPress path/to/file.php # Check entire plugin or theme ./vendor/bin/phpcs --standard=WordPress --extensions=php /path/to/plugin/ # Auto-fix issues where possible ./vendor/bin/phpcbf --standard=WordPress path/to/file.php ``` -------------------------------- ### CSS Inline Commenting Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/css.md This CSS example illustrates inline commenting practices. Comments are placed directly before or after the relevant code, with no extra newlines. It includes an example of explaining the necessity of using `!important` for specific style overrides. ```css /* This is a comment about this selector */ .another-selector { position: absolute; top: 0 !important; /* I should explain why this is so !important */ } ``` -------------------------------- ### PHP Function and Class Method Documentation Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Standard DocBlock format for PHP functions and class methods. Includes summary, detailed description, and various tags for versioning, access, references, globals, parameters, and return values. ```php /** * Summary. * * Description. * * @since x.x.x * * @see Function/method/class relied on * @link URL * @global type $varname Description. * @global type $varname Description. * * @param type $var Description. * @param type $var Optional. Description. Default. * @return type Description. */ ``` -------------------------------- ### Markdown Horizontal Rules Source: https://github.com/wordpress/wpcs-docs/blob/master/styleguide.md Shows the simple syntax for creating a horizontal rule using three consecutive hyphens. ```markdown --- ``` -------------------------------- ### Documenting PHP Class Constants with DocBlocks Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md This snippet illustrates the DocBlock format for documenting PHP class constants. It includes a summary, the `@since` tag for versioning, and the `@var` tag to define the type and description of the constant. ```php /** * Summary. * * @since x.x.x * @var type $var Description. */ const NAME = value; ``` -------------------------------- ### Documenting Duplicate PHP Hooks Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md When a hook is used multiple times, only the primary instance is fully documented. Subsequent instances should use a single-line comment referencing the file where the full documentation resides. ```php /** This action is documented in path/to/filename.php */ ``` ```php /** This filter is documented in path/to/filename.php */ ``` -------------------------------- ### PHP Constant DocBlock Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Shows the recommended format for documenting constants in PHP using DocBlocks. This includes a summary, `@since` tag, and `@var` tag for type and description. ```php /** * Summary. * * @since x.x.x (if available) * @var type $var Description. */ ``` -------------------------------- ### Correct Object Instantiation Syntax in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Shows the correct syntax for instantiating new object instances in PHP, requiring parentheses even when not strictly necessary and ensuring no space between the class name and the opening parenthesis. This applies to regular classes, anonymous classes, and static instantiation. ```php // Correct. $foo = new Foo(); $anonymous_class = new class( $parameter ) { ... }; $instance = new static(); ``` -------------------------------- ### Writing require/include Statements Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Use `require[_once]` or `include[_once]` without parentheses around the path. Ensure only one space between the keyword and the path. Prefer `require[_once]` for unconditional includes to prevent fatal errors if a file is not found. ```php // Correct. require_once ABSPATH . 'file-name.php'; // Incorrect. include_once ( ABSPATH . 'file-name.php' ); require_once __DIR__ . '/file-name.php'; ``` -------------------------------- ### PHP Documentation for Array Parameters Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Documenting array parameters within a function's DocBlock using hash notation. This format details the structure and expected values of the array, suitable for complex arguments. ```php /** * Summary. * * Description. * * @since x.x.x * * @param type $var Description. * @param array $args { * Optional. An array of arguments. * * @type type $key Description. Default 'value'. Accepts 'value', 'value'. * (aligned with Description, if wraps to a new line) * @type type $key Description. * } * @param type $var Description. * @return type Description. */ ``` -------------------------------- ### PHP Database Queries with wpdb->prepare() Source: https://context7.com/wordpress/wpcs-docs/llms.txt Ensures proper escaping and security for all database queries using the $wpdb->prepare() method. Supports integer (%d), float (%f), string (%s), and identifier (%i) placeholders. Avoids assignment in conditional statements for clarity. ```php // Correct - using $wpdb->prepare() for escaping $var = "dangerous'"; // Raw data that may need escaping $id = some_foo_number(); // Data expected to be an integer $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) ); // Available placeholders (do NOT quote these): // %d - integer // %f - float // %s - string // %i - identifier (table/field names) // Correct - get data from database $data = $wpdb->get_var( '...' ); if ( $data ) { // Use $data } // Incorrect - assignment in conditional if ( $data = $wpdb->get_var( '...' ) ) { // Don't do this // Use $data } ``` -------------------------------- ### Documenting Backbone.js Classes Without Initialize Functions using @inheritDoc Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/javascript.md Illustrates how to document Backbone.js classes that lack an `initialize` function by using the `@inheritDoc` tag. This method leverages JSDoc to inherit documentation from a parent or related class, though a known bug may affect its current functionality. ```javascript /** * Summary. (use period) * * Description. (use period) * * @since x.x.x * @deprecated x.x.x Use new_function_name() instead. * @access private * * @constructs namespace.Class * @memberOf namespace * @augments Parent * @mixes mixin * @inheritDoc * * @alias realName * @memberof namespace * * @see Function/class relied on * @link URL */ Class = Parent.extend( /** @lends namespace.Class.prototype */{ // Functions and properties. } ); ``` -------------------------------- ### Correct Import Use Statements in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Demonstrates the correct way to use import 'use' statements in PHP, following the specified order for namespaces, functions, and constants. It also shows the proper use of aliases and grouped imports. ```php namespace Project_Name\Feature; use Project_Name\Sub_Feature\Class_A; use Project_Name\Sub_Feature\Class_C as Aliased_Class_C; use Project_Name\Sub_Feature\{ Class_D, Class_E as Aliased_Class_E, } use function Project_Name\Sub_Feature\function_a; use function Project_Name\Sub_Feature\function_b as aliased_function; use const Project_Name\Sub_Feature\CONSTANT_A; use const Project_Name\Sub_Feature\CONSTANT_D as ALIASED_CONSTANT; // Rest of the code. ``` -------------------------------- ### Format Multi-line Inline Comments Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/javascript.md Illustrates the correct formatting for multi-line inline comments in WordPress JavaScript. Emphasizes using a single asterisk and avoiding double asterisks at the start. ```javascript /* * This is a comment that is warranted being stretched over * the span of multiple lines. You'll notice this follows basically * the same format as the JSDoc wrapping and comment block style. */ ``` -------------------------------- ### PHP File Header DocBlock Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/php.md Illustrates the standard format for file header DocBlocks in WordPress. This DocBlock provides an overview of the file's purpose and should be included in all WordPress files. ```php /** * Summary (no period for file headers) * * Description. (use period) * * @link URL * * @package WordPress * @subpackage Component * @since x.x.x (when the file was introduced) */ ``` -------------------------------- ### Document PHP Classes with Summary and @since Source: https://context7.com/wordpress/wpcs-docs/llms.txt Documents PHP classes using PHPDoc format, including a summary, detailed description, and the @since tag to indicate the version the class was introduced. It also requires documenting all properties and methods. ```php /** * Core class for handling user authentication. * * Manages user login, logout, and session handling for WordPress. * Implements secure cookie-based authentication with optional * remember-me functionality. * * @since 2.5.0 * * @see WP_Session_Tokens */ class WP_User_Auth { /** * The user ID. * * @since 2.5.0 * @var int */ public $user_id; /** * Whether the user is authenticated. * * @since 2.5.0 * @var bool */ private $authenticated = false; /** * Authenticates a user with credentials. * * @since 2.5.0 * * @param string $username User login name. * @param string $password User password. * @return WP_User|WP_Error WP_User on success, WP_Error on failure. */ public function authenticate( $username, $password ) { // Implementation } } ``` -------------------------------- ### PHP Type Declarations: Incorrect Syntax Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Illustrates common mistakes in PHP type declarations, such as incorrect spacing, casing, and the use of the nullability operator. This serves as a guide to avoid these errors. ```php // Incorrect. function baz(Class_Name $param_a, String$param_b, CALLABLE $param_c ) : ? iterable { // Do something. } ``` -------------------------------- ### SCREAMING_SNAKE_CASE for Constants in JavaScript Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md This example shows the SCREAMING_SNAKE_CASE convention for constant values in JavaScript that are never intended to be reassigned or mutated. These constants are typically defined in the top-most scope of a file to communicate intent. ```javascript const MAX_CONNECTIONS = 10; const API_KEY = "your_api_key_here"; ``` -------------------------------- ### Format SQL Statements with $wpdb->prepare() in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Demonstrates how to format SQL statements securely and readably in PHP using the `$wpdb->prepare()` method. This method handles escaping, quoting, and type casting for SQL queries, preventing SQL injection vulnerabilities. It uses `sprintf()` style placeholders like %d, %f, %s, and %i. ```php $var = "dangerous'"; // Raw data that may or may not need to be escaped. $id = some_foo_number(); // Data we expect to be an integer, but we're not certain. $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) ); ``` -------------------------------- ### Prioritize Readability Over Cleverness in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Highlights the importance of writing clear and understandable code over concise or 'clever' one-liners. It provides examples of how to refactor complex or obscure code snippets into more straightforward `if` statements for better maintainability. ```php // Clever but less readable. isset( $var ) || $var = some_function(); // More readable. if ( ! isset( $var ) ) { $var = some_function(); } ``` -------------------------------- ### PHP Array Declaration with Explicit Keys Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Illustrates the standard for declaring PHP arrays with explicit keys, where each item starts on a new line if the array contains more than one item. This enhances readability for associative arrays. ```php $args = array( 'post_type' => 'page', 'post_author' => 123, 'post_status' => 'publish', ); $query = new WP_Query( $args ); ``` -------------------------------- ### Incorrect Visibility Declarations in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Highlights incorrect practices for visibility declarations in PHP, specifically the use of the 'var' keyword for properties and the omission of explicit visibility modifiers for methods. These examples violate WordPress coding standards. ```php // Incorrect. class Foo { var $foo; function bar() {} } ``` -------------------------------- ### JavaScript Variables and Globals Source: https://context7.com/wordpress/wpcs-docs/llms.txt Explains the use of `const` and `let` for modern JavaScript, or a single `var` statement for older code. Includes guidance on documenting global variables and safely accessing the `wp` global object, along with using jQuery within an anonymous function. ```javascript // ES2015+ - prefer const, use let only when reassignment needed const userId = 1; let counter = 0; // Pre-ES2015 - single var statement with comma separation var k, m, length, // Indent subsequent lines by one tab value = 'WordPress'; // Declaring globals for JSHint /* global passwordStrength:true */ // Safely accessing wp global window.wp = window.wp || {}; // jQuery in anonymous function ( function ( $ ) { // Use $ safely here } )( jQuery ); ``` -------------------------------- ### Object-Oriented Programming: One Class per File in PHP Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/php.md Enforces the WordPress coding standard of having only one object structure (class, interface, trait, or enum) per file. This example shows both incorrect and correct file structures. ```php // Incorrect: file class-example-class.php. class Example_Class {} class Example_Class_Extended {} ``` ```php // Correct: file class-example-class.php. class Example_Class {} ``` ```php // Correct: file class-example-class-extended.php. class Example_Class_Extended {} ``` -------------------------------- ### Documenting Local Functions as Inner Functions with `~` Alias Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/javascript.md Explains how to document local functions assigned to variables before becoming class members. It shows how to mark these as inner functions of a namespace using the `~` alias in JSDoc and how to borrow their documentation using `@borrows`. ```javascript /** * Function description, you can use any JSDoc here as long as the function remains private. * * @alias namespace~doStuff */ var doStuff = function () { // Do stuff. }; Class = Parent.extend( /** @lends namespace.Class.prototype */{ /** * Class description * * @constructs namespace.Class * * @borrows namespace~doStuff as prototype.doStuff */ initialize: function() { //Do stuff. }, /* * This function will automatically have it's documentation copied from above. * You should make a comment ( not a DocBlock using /**, instead use /* or // ) * noting that you're describing this function using @borrows. */ doStuff: doStuff, } ); ``` -------------------------------- ### Standard JSDoc Function Documentation in JavaScript Source: https://github.com/wordpress/wpcs-docs/blob/master/inline-documentation-standards/javascript.md This snippet demonstrates the standard JSDoc format for documenting JavaScript functions according to WordPress coding standards. It includes common tags for describing the function's purpose, versioning, access level, parameters, return values, and relationships with other code elements. ```javascript /** * Summary. (use period) * * Description. (use period) * * @since x.x.x * @deprecated x.x.x Use new_function_name() instead. * @access private * * @class * @augments parent * @mixes mixin * * @alias realName * @memberof namespace * * @see Function/class relied on * @link URL * @global * * @fires eventName * @fires className#eventName * @listens event:eventName * @listens className~event:eventName * * @param {type} var Description. * @param {type} [var] Description of optional variable. * @param {type} [var=default] Description of optional variable with default variable. * @param {Object} objectVar Description. * @param {type} objectVar.key Description of a key in the objectVar parameter. * * @yield {type} Yielded value description. * * @return {type} Return value description. */ ``` -------------------------------- ### PHP Yoda Conditions for WordPress Source: https://context7.com/wordpress/wpcs-docs/llms.txt Promotes placing constants, literals, or function calls on the left side of comparisons to prevent accidental assignment bugs. Enhances code safety by avoiding common assignment errors. Example shows correct and incorrect usage. ```php // Correct - Yoda conditions if ( true === $the_force ) { $victorious = you_will( $be ); } if ( 0 === strpos( $text, 'WordPress' ) ) { echo esc_html__( 'Yay WordPress!', 'textdomain' ); } // Incorrect - variable on left could lead to bugs if ( $the_force = true ) { // Bug! Assignment instead of comparison // This would always execute } ``` -------------------------------- ### JavaScript Object Creation and Access Source: https://github.com/wordpress/wpcs-docs/blob/master/wordpress-coding-standards/javascript.md Illustrates the recommended way to create JavaScript objects using object literal notation `{}` for performance and readability. It also covers accessing object properties using dot notation and bracket notation when keys are variables or contain special characters. ```javascript var myObj = {}; ``` ```javascript var myObj = new ConstructorMethod(); ``` ```javascript prop = object.propertyName; prop = object[ variableKey ]; prop = object['key-with-hyphens']; ```