You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: wordpress-coding-standards/php.md
+23-25Lines changed: 23 additions & 25 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,9 +6,7 @@ Keep the following points in mind when writing PHP code for WordPress, whether f
6
6
7
7
See also: [PHP Inline Documentation Standards](https://developer.wordpress.org/coding-standards/inline-documentation-standards/php/).
8
8
9
-
## PHP
10
-
11
-
### Single and Double Quotes
9
+
## Single and Double Quotes
12
10
13
11
Use single and double quotes when appropriate. If you're not evaluating anything in the string, use single quotes. You should almost never have to escape quotes in a string, because you can just alternate your quoting style, like so:
Text that goes into attributes should be run through `esc_attr()` so that single or double quotes do not end the attribute value and invalidate the HTML and cause a security issue. See [Data Validation](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
21
19
22
-
###Indentation
20
+
## Indentation
23
21
24
22
Your indentation should always reflect logical structure. Use **real tabs** and **not spaces**, as this allows the most flexibility across clients.
25
23
@@ -74,7 +72,7 @@ switch ( $type ) {
74
72
75
73
**Rule of thumb:** Tabs should be used at the beginning of the line for indentation, while spaces can be used mid-line for alignment.
76
74
77
-
###Brace Style
75
+
## Brace Style
78
76
79
77
Braces shall be used for all blocks in the style shown here:
80
78
@@ -125,17 +123,17 @@ Note that requiring the use of braces just means that _single-statement inline c
125
123
<?php endif; ?>
126
124
```
127
125
128
-
###Use `elseif`, not `else if`
126
+
## Use `elseif`, not `else if`
129
127
130
128
`else if` is not compatible with the colon syntax for `if|elseif` blocks. For this reason, use `elseif` for conditionals.
131
129
132
-
###Declaring Arrays
130
+
## Declaring Arrays
133
131
134
132
Using long array syntax ( `array( 1, 2, 3 )` ) for declaring arrays is generally more readable than short array syntax ( `[ 1, 2, 3 ]` ), particularly for those with vision difficulties. Additionally, it's much more descriptive for beginners.
135
133
136
134
Arrays must be declared using the long array syntax.
137
135
138
-
###Closures (Anonymous Functions)
136
+
## Closures (Anonymous Functions)
139
137
140
138
Where appropriate, closures may be used as an alternative to creating new functions to pass as callbacks. For example:
Closures must not be passed as filter or action callbacks, as they cannot be removed by `remove_action()` / `remove_filter()` (see [#46635](https://core.trac.wordpress.org/ticket/46635"Improve identifying of non–trivial callbacks in hooks") for a proposal to address this).
153
151
154
-
###Multiline Function Calls
152
+
## Multiline Function Calls
155
153
156
154
When splitting a function call over multiple lines, each parameter must be on a separate line. Single line inline comments can take up their own line.
157
155
@@ -176,13 +174,13 @@ $a = foo(
176
174
);
177
175
```
178
176
179
-
###Regular Expressions
177
+
## Regular Expressions
180
178
181
179
Perl compatible regular expressions ([PCRE](https://www.php.net/pcre), `preg_` functions) should be used in preference to their POSIX counterparts. Never use the `/e` switch, use `preg_replace_callback` instead.
182
180
183
181
It's most convenient to use single-quoted strings for regular expressions since, contrary to double-quoted strings, they have only two metasequences: `\'` and `\\`.
184
182
185
-
###Opening and Closing PHP Tags
183
+
## Opening and Closing PHP Tags
186
184
187
185
When embedding multi-line PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.
188
186
@@ -217,7 +215,7 @@ if ( $a === $b ) { ?>
217
215
<?php }
218
216
```
219
217
220
-
###No Shorthand PHP Tags
218
+
## No Shorthand PHP Tags
221
219
222
220
**Important:** Never use shorthand PHP start tags. Always use full PHP tags.
223
221
@@ -235,11 +233,11 @@ Incorrect:
235
233
<?= $var ?>
236
234
```
237
235
238
-
###Remove Trailing Spaces
236
+
## Remove Trailing Spaces
239
237
240
238
Remove trailing whitespace at the end of each line of code. Omitting the closing PHP tag at the end of a file is preferred. If you use the tag, make sure you remove the trailing whitespace.
241
239
242
-
###Space Usage
240
+
## Space Usage
243
241
244
242
Always put spaces after commas, and on both sides of the logical, comparison, string, and assignment operators.
When formatting SQL statements you may break them into several lines and indent if it is sufficiently complex to warrant it. Most statements work well as one line though. Always capitalize the SQL parts of the statement like `UPDATE` or `WHERE`.
331
329
@@ -344,13 +342,13 @@ $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID
344
342
345
343
See [Data Validation](https://developer.wordpress.org/plugins/security/data-validation/) in the Plugin Handbook for further details.
346
344
347
-
###Database Queries
345
+
## Database Queries
348
346
349
347
Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.
350
348
351
349
If you must touch the database, get in touch with some developers by posting a message to the [wp-hackers mailing list](https://codex.wordpress.org/Mailing_Lists#Hackers). They may want to consider creating a function for the next WordPress version to cover the functionality you wanted.
352
350
353
-
###Naming Conventions
351
+
## Naming Conventions
354
352
355
353
Use lowercase letters in variable, action/filter, and function names (never `camelCase`). Separate words via underscores. Don't abbreviate variable names unnecessarily; let the code be unambiguous and self-documenting.
356
354
@@ -391,7 +389,7 @@ Files containing template tags in `wp-includes` should have `-template` appended
391
389
general-template.php
392
390
```
393
391
394
-
###Only one object structure (class/interface/trait) declared per file
392
+
## Only one object structure (class/interface/trait) declared per file
395
393
396
394
For instance, if we have a file called `class-example-class.php` it can only contain one class in that file.
397
395
@@ -414,7 +412,7 @@ class Example_Class { [...] }
414
412
class Example_Class_Extended { [...] }
415
413
```
416
414
417
-
###Self-Explanatory Flag Values for Function Arguments
415
+
## Self-Explanatory Flag Values for Function Arguments
418
416
419
417
Prefer string values to just `true` and `false` when calling functions.
420
418
@@ -450,7 +448,7 @@ function eat( $what, $args ) {
Where possible, dynamic values in tag names should also be as succinct and to the point as possible. `$user_id` is much more self-documenting than, say, `$this->id`.
466
464
467
-
###Ternary Operator
465
+
## Ternary Operator
468
466
469
467
[Ternary operators](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary) are fine, but always have them test if the statement is true, not false. Otherwise, it just gets confusing. (An exception would be using `! empty()`, as testing for false here is generally more intuitive.)
// (if field is not empty ) ? (do this) : (else, do this);
479
477
```
480
478
481
-
###Yoda Conditions
479
+
## Yoda Conditions
482
480
483
481
```php
484
482
if ( true === $the_force ) {
@@ -494,7 +492,7 @@ A little bizarre, it is, to read. Get used to it, you will.
494
492
495
493
This applies to `==`, `!=`, `===`, and `!==`. Yoda conditions for `<`, `>`, `<=` or `>=` are significantly more difficult to read and are best avoided.
496
494
497
-
###Clever Code
495
+
## Clever Code
498
496
499
497
In general, readability is more important than cleverness or brevity.
500
498
@@ -570,7 +568,7 @@ The `goto` statement must never be used.
570
568
571
569
The `eval()` construct is _very dangerous_ and is impossible to secure. Additionally, the `create_function()` function, which internally performs an `eval()`, is deprecated in PHP 7.2. Neither of these must be used.
572
570
573
-
###Error Control Operator `@`
571
+
## Error Control Operator `@`
574
572
575
573
As noted in the [PHP docs](https://www.php.net/manual/en/language.operators.errorcontrol.php):
576
574
@@ -580,7 +578,7 @@ While this operator does exist in Core, it is often used lazily instead of doing
580
578
581
579
> Warning: Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.
582
580
583
-
###Don't `extract()`
581
+
## Don't `extract()`
584
582
585
583
Per [#22400](https://core.trac.wordpress.org/ticket/22400"Remove all, or at least most, uses of extract() within WordPress"):
0 commit comments