SlideShare a Scribd company logo
In-Depth Guide On WordPress Coding Standards For
PHP, HTML
“ANY FOOL CAN WRITE A CODE THAT COMPUTER CAN UNDERSTAND. GOOD
PROGRAMMERS WRITE CODE THAT HUMAN CAN UNDERSTAND.”
- JOHN JOHNSON
This quote is good enough to understand the importance of standards as far as the coding is
concerned. Every programming language has its own rules and regulations for the coding which is
also known as the coding standards.
Each programmer should follow these coding standards in order to inherit the best practices in
his/her professional career. Coding standards are not the syntax that strictly needs to be followed,
they are more of coding conventions that if followed by the programmer can help them to enhance
their coding style.
The same applies to the case of WordPress where it has its own coding standards which every
developer should have the knowledge of. Taking this into consideration, we have developed a
two-part series on WordPress Coding Standards which will help you to know the coding standards
for PHP, HTML, CSS, & JS.
Here’s how we will progress right through the WordPress Coding Standards series:
Part 1: In-Depth Guide On WordPress Coding Standards For PHP & HTML
Part 2: In-Depth Guide On WordPress Coding Standards For CSS & JS
In this blog, we will focus on part 1 - WordPress Coding Standards For PHP & HTML and in the
next blog, we will focus on part 2 - WordPress Coding Standards For CSS & JS.
Before going to into the details of WordPress Coding Standards, you need to know the purpose of
the coding standards & why you need to have coding standards.
What Is The Purpose Of WordPress Coding Standards?
The sole purpose of the WordPress Coding Standards is to create a base for collaboration and
review within the various aspects of WordPress open-source project & community right from the
core part to the themes and plugins.
Why You Need Coding Standards?
Coding standards help you to avoid common errors, simplify the modification process & most
importantly assists you in improving the readability of your code.
In addition to all these, the coding standards ensure that all files within one project appear as if
they’re created by a single person.
Another major advantage you get by following the coding standards is that anyone will be able to
understand your code and also modify it, without contacting you.
So, if you’re planning to develop a website in WordPress, you should know the coding standards.
Now, let’s dive deep into the core part & understand the various coding standards.
Part 1: In-Depth Guide On WordPress Coding
Standards For PHP & HTML:-
WordPress Coding Standards For PHP
1. Using Single & Double Quotes
If you’re someone who is working in a Custom WordPress Development Company, then you
must be knowing that appropriate use of single and double quotes is necessary.
As per the standard convention if you’re not evaluating anything in the string, then you should use
the single quotes. Otherwise, you should always prefer using the double quotes for the string value
while writing PHP code for the WordPress platform.
Example:
echo '<a href="www.url.com" title="Contact">Contact Us</a>';
echo "<a href='$cta_link' title='$cta_title'>$cta_label</a>";
Here, we have used double quotes for displaying the “Contact” as it is a value for the title attribute,
while we have used a single quote for ‘$cta_title’ as we’re not evaluating its value.
2. Indentation
Another very important thing that you need to remember while writing the code in PHP is the
proper use of indentation. The reason behind that is, it always reflects the logical structure of your
code. Always use tabs for indentation instead of space, as it improves readability.
However, there is one exception: If you've got a block of code which looks more readable if the
code is written in an aligned manner, then you can use space for that purpose.
Example:
[tab]'demo' => 'demovalue';
[tab]'demo1' => 'demovalue1’;
[tab]'demo2' => 'demovalue2';
[tab]'demo3' => 'demovalue3';
For associative arrays, each item should start on a new line when the array contains more than one
item:
Example:
$key_value_array = array(
[tab]'demo' => 'demovalue',
[tab]'demo1' => 'demovalue1',
[tab]'demo2' => 'demovalue2',
[tab]'demo3' => 'demovalue3',
);
Here, you may have noted a comma after the last item. This is recommended by the WordPress as
it makes it easier for you to change the order of an array.
Example:
[tab]'demo3' => 'demovalue3',
[tab]'demo1' => 'demovalue1',
[tab]'demo' => 'demovalue',
[tab]'demo2' => 'demovalue2',
);
For the switch structures, the case should be indented one tab from the switch statement and
break should be one tab from the case statement.
Example:
switch ( $condition ) {
[tab]case 'value':
[tab][tab]demo_function();
[tab][tab]break;
[tab]case 'value2':
[tab][tab]demo_function1();
[tab][tab]break;
}
As a thumb rule, Tabs should be used at the beginning of the line for indentation and Space should
be used for the mid-line alignment.
3. Brace Style
Braces should be used for all the blocks as shown in the snippet below:
Example:
if ( condition ) {
function();
function2();
} elseif ( condition2 && condition3 ) {
function3();
function4();
} else {
defaul_function();
}
In case, you have a really long block, it can be broken into 2 or more shorter blocks to reduce
complexity and improve readability.
Example:
if ( condition ) {
function();
function2();
} elseif ( condition2 && condition3 ) {
function3();
function4();
} else {
defaul_function();
}
foreach ( $data as $data_key => $data_value ) {
echo $data_value;
}
One thing that should be noted here is that the use of braces is to avoid single-statement inline
control structures. You’re free to use the alternative syntax for control structure, especially when
the PHP code is embedded into the HTML.
Example:
<?php if ( !empty( $data ) ) { ?>
<div class="test">
<?php foreach ( $data as $data_key => $data_value ) { ?>
<div id="data-<?php echo $data_key; ?>">
<!-- Other Content -->
</div>
<?php } ?>
</div>
<?php } ?>
4. Use elseif, Not else if
else if is not compatible with the colon-based syntax for if|elseif blocks. Therefore, you should
always use elseif instead of using else if.
5. Multiline Function Calls
As a WordPress developer, when you split the function call over the multiple lines, always
remember to keep each parameter on a separate line.
Each parameter should not consume more than one line and multiline parameter values must be
assigned to a variable, so you just need to pass that variable to the function call.
Example:
```
$bar = array(
'use_this' => true,
'meta_key' => 'field_name',
);
$baz = sprintf(
/* translators: %s: Friend's name */
esc_html__( 'Hello, %s!', 'yourtextdomain' ),
$friend_name
);
$a = foo(
$bar,
$baz,
/* translators: %s: cat */
sprintf( __( 'The best pet is a %s.' ), 'cat' )
);
6. Regular Expressions
Always use Perl compatible regular expressions (PCRE) with the reference to their POSIX
counterparts. Never use the /e switch, use preg_replace_callback instead. In addition to all these,
you should always use single-quoted strings for the regular expressions.
7. Opening & Closing PHP Tags
When you’re embedding multiline PHP snippets within an HTML block, the PHP open and close
tags must be on a line by themselves.
Example: (multiline)
function test_function() {
?>
<div>
<?php
echo '<a href="www.url.com" title="Contact">Contact Us</a>';
?>
</div>
<?php
}
Example: (single line)
<input type="text" name="<?php echo $name ; ?>" />
8. No Shorthand PHP Tags
Never use shorthand PHP tags, always use full PHP tags.
Example: (Incorrect)
```
<? ... ?>
<?= $var ?>
Example: (Correct)
```
<?php ... ?>
<?php echo $var; ?>
9. Remove Trailing Spaces
Always remember to remove the trailing whitespaces at the end of your each coding line. You
should omit the PHP tag at the end of the file. However, if you’re using the tag, then don’t forget to
remove the trailing whitespace.
10. Proper Usage Of Space
Always put space after every comma and also on both sides of logical, comparison, string and
assignment operators.
Example:
y == 2
foo && bar
! foo
array( 1, 2, 3 )
$baz . '-4'
$term .= 'Z'
Remember to put spaces on both sides opening and closing parentheses of if, elseif, foreach, for,
and switch blocks.
Example:
```
foreach ( $foo as $bar ) { …
Also, follow this rule while defining a function.
Example:
function dummy( $param1 = 'foo', $param2 = 'bar' ) { ...
function my_dummy_function1() { ...
When you’re calling any function, you need to follow the rule mentioned above.
Example:
first_function1( $param1, func_param( $param2 ) );
my_dummy_function();
For logical comparisons, the same rule applies.
Example:
```
if ( ! $foo ) { ...
When you’re performing typecasting, the above rule is also valid.
Example:
```
foreach ( (array) $foo as $bar ) { ...
$foo = (boolean) $bar;
When referring to array items, include a space around the index only if it’s variable.
Example:
$x = $foo['bar']; // correct
$x = $foo[ 'bar' ]; // incorrect
$x = $foo[0]; // correct
$x = $foo[ 0 ]; // incorrect
$x = $foo[ $bar ]; // correct
$x = $foo[$bar]; // incorrect
For a switch block, there should be any space before the colon for a case statement.
Example:
```
switch ( $foo ) {
case 'bar': // correct
case 'ba' : // incorrect
}
Similarly, there should be no space before the colon on the return type declaration.
Example:
```
function sum( $a, $b ): float {
return $a + $b;
}
11. Formatting SQL Statements
When you’re formatting any SQL statement, you should break it into several lines and indent if it’s
sufficiently complex. Always capitalize the SQL parts of the statements such as WHERE or
UPDATE.
Functions that update the database should expect their parameters to lack SQL slash escaping
when passed. For that purpose, escaping should be done by using $wpdb->prepare().
$wpdb->prepare() is a method that handles escaping, quoting and int-casting for SQL queries.
Example:
<?php
// set the meta_key to the appropriate custom field meta key
$meta_key = 'miles';
$allmiles = $wpdb->get_var( $wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$meta_key
) );
echo "<p>Total miles is {$allmiles}</p>";
?>
Here, %s is used for string placeholders and %d is used for integer placeholders. Note that they
are not ‘quoted’! $wpdb->prepare() will take care of escaping and quoting for us. This is the
benefit you get if you utilize this function.
12. Database Queries
Always avoid touching the database in a direct manner. Utilize the functions for extracting the data
whenever possible. The reason behind that is, Database Abstraction (using functions in place of
queries) helps you to keep your code forward-compatible.
13. Naming Conventions
Always use lowercase for a variable, action/filter, and function names. Separate the words by
using underscore. In addition to that, choose a name which is unambiguous & self-documenting.
Example:
function some_name( $some_variable ) { [...] }
For class name, you should use capitalize words which are separated by underscores.
Example:
```
class Walk_Categorization extends Walk { [...] }
All the constants should be in upper-case with words being separated by underscores.
Example:
```
define( 'PI', true );
The file should be named descriptively by using the lowercase and for separating the words you
should utilize hyphen.
My-new-theme.php
For class file name should be based on the class name i.e. class- followed by a hyphen.
Example:
If the class name is class Walk_Categorization, then the class file name should be
class-walk-categroization.php
There is one exception in the class file name for three files: class.wp-dependencies.php,
class.wp-scripts.php, class.wp-styles.php. These files are ported into Backpress and therefore,
they are prepended with class. instead of a hyphen.
14. Self-Explanatory Flag Values for Function Arguments
Always prefer using true & false for the string values when you're calling a function.
Example:
// Incorrect
function eat( $what, $slowly = true ) {
...
}
eat( 'wheat', true );
eat( 'rice', false );
Now, PHP doesn’t support flag arguments and therefore, sometimes the values of flags are
meaningless as it is in our example shown above. So, for that type of scenario, you should make
your code readable by utilizing descriptive string values instead of booleans.
Example:
// Correct
function eat( $what, $slowly = ‘slowly’) {
...
}
eat( 'wheat', ‘slowly’ );
eat( 'rice', ‘quickly’ );
15. Interpolation for Naming Dynamic Hooks
For naming the dynamic hooks, you should utilize the interpolation methodology rather than using
the concatenation for readability purpose. Dynamic hooks are the one which includes dynamic
values in their tag name - {$new_status}_{$post->post_type} (publish_post).
Always include the variables of your hook tags inside the curly braces {} and the outer tag name
should be wrapped in double quotes. The reason behind following this methodology is to ensure
that PHP can correctly parse the variable types with interpolated string:
Example:
```
do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
16. Ternary Operator
For using the ternary operator, always have them test if the statement is true, not false. Otherwise,
it can create a massive confusion in the future.
Example:
```
$musictype = ( 'jazz' == $music ) ? 'cool' : 'blah';
17. Yoda Conditions
When you’re doing the logical comparisons which include variables, always put the variable on
the right-hand side & constants, literals, or function calls on the left-hand side. If neither side has a
variable, then the order is not that important.
Example:
```
if ( true == $the_force ) {
$victorious = you_will( $be );
}
Here, if you omit an equals sign (=), then you will get a parse error, as you can’t assign a value to
constant like true. Instead of that, if you’ve written ( $the_force = true ), the assignment would be
perfect and you won’t get an error. This is known as the Yoda Condition and it applies to ==, !=,
===, !==, <, >, <= or >= operators.
18. Clever Coding
For coding, readability is more important than cleverness.
Example:
```
isset( $var ) || $var = some_function();
This might look clever, but it has low readability. Instead of that, if you write:
if ( ! isset( $var ) ) {
$var = some_function();
}
Then, the readability improves drastically.
In the case of a switch statement, it’s ok to have multiple cases in a common block. However, if a
case contains a block, the falls through to the next block, then this should be explicitly commented
as shown in the snippet below:
switch ( $foo ) {
case 'bar': // Correct, an empty case can fall through without comment.
case 'baz':
echo $foo; // Incorrect, a case with a block must break, return, or
have a comment.
case 'cat':
echo 'mouse';
break; // Correct, a case with a break does not require a comment.
case 'dog':
echo 'horse';
// no break // Correct, a case can have a comment to explicitly mention
the fall-through.
case 'fish':
echo 'bird';
break;
}
WordPress Coding Standards For HTML
1. Validation
All the HTML pages should be verified with the help of the W3C Validator to ensure that markup
is well-formed. Although this is not the only indicator of good coding, it helps to solve the
problems that are to be tested via the automation process. The manual code review cannot be as
effective as this one and that’s why it is recommended that you should validate your code.
2. Self-Enclosing Elements
All tags must be properly closed. Howver, for the tags that are self-enclosing, the forward slash
should have once space preceding it.
Example:
```
<br /> //Correct
<br/> //Incorrect
3. Attributes & Tags
All the tags, as well as their attributes, must be written in lowercase. In addition to that, attribute
values should be in lowercase when the purpose of the text is just to be interpreted by a machine.
However, when an attribute value is going be read by a human, proper capitalization should
follow:
Example:
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> // For
Machine
<a href="http://abc.com/" title="Content Writer">ABC.com</a> // For Human
4. Quotes
As per the W3C specification for XHTML, all the attributes must have a value & must be wrapped
inside single or double quotes.
Example:
```
<input type="text" name="ABC" disabled="disabled" /> //Correct
<input type='text' name=’ABC’ disabled='disabled' /> //Correct
<input type=text name=email disabled>//Incorrect
Howver, in HTML all attributes do not have to have values & they do not have to be quoted. But
you should follow these conventions to avoid any kind of security vulnerabilities.
5. Indentation
Like PHP, HTML indentation should always reflect logical structure. So always use tabs and not
spaces. If you’re mixing PHP & HTML, then indent PHP blocks to match the HTML code.
Example:
?php if ( ! have_posts() ) : ?>
<div id="post-1" class="post">
<h1 class="entry-title">Not Found</h1>
<div class="entry-content">
<p>Apologies, but no results were found.</p>
<?php get_search_form(); ?>
</div>
</div>
<?php endif; ?>
Final Thoughts…
Every programming language has its own coding standards which need to be followed by the
programmer in order to enhance the readability of the code. The same is the case with WordPress,
where there are coding standards for PHP, HTML, CSS & JS.
Here, we have tried to provide you with an in-depth guide on WordPress Coding Standards For
PHP & HTML which will help you in future when you're developing something in WordPress.
If you’ve any question or suggestion regarding this subject, then do mention them in our comment
section. Thank You!
Originally Published at esparkinfo.com

More Related Content

What's hot

Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
Tharcius Silva
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kianphelios
 
Flex Maniacs 2007
Flex Maniacs 2007Flex Maniacs 2007
Flex Maniacs 2007
rtretola
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
McSoftsis
 
Dsl
DslDsl
Dsl
phoet
 
Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
Striving towards better PHP code
Striving towards better PHP codeStriving towards better PHP code
Striving towards better PHP code
Steve Maraspin
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
Sopan Shewale
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
bergonio11339481
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
keeyre
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunctionADARSH BHATT
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technologyppparthpatel123
 
Cena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 SlidesCena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 Slides
Asao Kamei
 
Perl programming language
Perl programming languagePerl programming language
Perl programming languageElie Obeid
 
Introduction to Python by Wekanta
Introduction to Python by WekantaIntroduction to Python by Wekanta
Introduction to Python by Wekanta
Wekanta
 
Ruby_Coding_Convention
Ruby_Coding_ConventionRuby_Coding_Convention
Ruby_Coding_ConventionJesse Cai
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
Varadharajan Mukundan
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
kalaisai
 
No comment
No commentNo comment
No comment
natedavisolds
 

What's hot (20)

Ruby quick ref
Ruby quick refRuby quick ref
Ruby quick ref
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Flex Maniacs 2007
Flex Maniacs 2007Flex Maniacs 2007
Flex Maniacs 2007
 
Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Dsl
DslDsl
Dsl
 
Php string function
Php string function Php string function
Php string function
 
Striving towards better PHP code
Striving towards better PHP codeStriving towards better PHP code
Striving towards better PHP code
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Cena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 SlidesCena-DTA PHP Conference 2011 Slides
Cena-DTA PHP Conference 2011 Slides
 
Smarty 3 overview
Smarty 3 overviewSmarty 3 overview
Smarty 3 overview
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Introduction to Python by Wekanta
Introduction to Python by WekantaIntroduction to Python by Wekanta
Introduction to Python by Wekanta
 
Ruby_Coding_Convention
Ruby_Coding_ConventionRuby_Coding_Convention
Ruby_Coding_Convention
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 
No comment
No commentNo comment
No comment
 

Similar to In-Depth Guide On WordPress Coding Standards For PHP & HTML

Php
PhpPhp
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Php
PhpPhp
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
GTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesGTU PHP Project Training Guidelines
GTU PHP Project Training Guidelines
TOPS Technologies
 
What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics EbookSwanand Pol
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
AhmedAElHalimAhmed
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 

Similar to In-Depth Guide On WordPress Coding Standards For PHP & HTML (20)

Php
PhpPhp
Php
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php
PhpPhp
Php
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Coding standard
Coding standardCoding standard
Coding standard
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Programming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th SemesterProgramming in PHP Course Material BCA 6th Semester
Programming in PHP Course Material BCA 6th Semester
 
GTU PHP Project Training Guidelines
GTU PHP Project Training GuidelinesGTU PHP Project Training Guidelines
GTU PHP Project Training Guidelines
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
phptutorial
phptutorialphptutorial
phptutorial
 
PHP Basics Ebook
PHP Basics EbookPHP Basics Ebook
PHP Basics Ebook
 
phptutorial
phptutorialphptutorial
phptutorial
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
 
Introduction to-php
Introduction to-phpIntroduction to-php
Introduction to-php
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 

More from eSparkBiz

Securing IoT Data With Blockchain - A New Age Innovation
Securing IoT Data With Blockchain - A New Age InnovationSecuring IoT Data With Blockchain - A New Age Innovation
Securing IoT Data With Blockchain - A New Age Innovation
eSparkBiz
 
Part 2 in depth guide on word-press coding standards for css &amp; js big
Part 2  in depth guide on word-press coding standards for css &amp; js bigPart 2  in depth guide on word-press coding standards for css &amp; js big
Part 2 in depth guide on word-press coding standards for css &amp; js big
eSparkBiz
 
12 innovative ways to utilize forms on word press website
12 innovative ways to utilize forms on word press website12 innovative ways to utilize forms on word press website
12 innovative ways to utilize forms on word press website
eSparkBiz
 
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
eSparkBiz
 
The best method that helps HubSpot website designer to be expert in hubspot cos
The best method that helps HubSpot website designer to be expert in hubspot cosThe best method that helps HubSpot website designer to be expert in hubspot cos
The best method that helps HubSpot website designer to be expert in hubspot cos
eSparkBiz
 
Website redesign process | Website Design & Development Company in USA
Website redesign process | Website Design & Development Company in USAWebsite redesign process | Website Design & Development Company in USA
Website redesign process | Website Design & Development Company in USA
eSparkBiz
 

More from eSparkBiz (6)

Securing IoT Data With Blockchain - A New Age Innovation
Securing IoT Data With Blockchain - A New Age InnovationSecuring IoT Data With Blockchain - A New Age Innovation
Securing IoT Data With Blockchain - A New Age Innovation
 
Part 2 in depth guide on word-press coding standards for css &amp; js big
Part 2  in depth guide on word-press coding standards for css &amp; js bigPart 2  in depth guide on word-press coding standards for css &amp; js big
Part 2 in depth guide on word-press coding standards for css &amp; js big
 
12 innovative ways to utilize forms on word press website
12 innovative ways to utilize forms on word press website12 innovative ways to utilize forms on word press website
12 innovative ways to utilize forms on word press website
 
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
13 Misunderstanding about HubSpot COS Development Platform & HubSpot COS Temp...
 
The best method that helps HubSpot website designer to be expert in hubspot cos
The best method that helps HubSpot website designer to be expert in hubspot cosThe best method that helps HubSpot website designer to be expert in hubspot cos
The best method that helps HubSpot website designer to be expert in hubspot cos
 
Website redesign process | Website Design & Development Company in USA
Website redesign process | Website Design & Development Company in USAWebsite redesign process | Website Design & Development Company in USA
Website redesign process | Website Design & Development Company in USA
 

Recently uploaded

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

In-Depth Guide On WordPress Coding Standards For PHP & HTML

  • 1. In-Depth Guide On WordPress Coding Standards For PHP, HTML “ANY FOOL CAN WRITE A CODE THAT COMPUTER CAN UNDERSTAND. GOOD PROGRAMMERS WRITE CODE THAT HUMAN CAN UNDERSTAND.” - JOHN JOHNSON This quote is good enough to understand the importance of standards as far as the coding is concerned. Every programming language has its own rules and regulations for the coding which is also known as the coding standards. Each programmer should follow these coding standards in order to inherit the best practices in his/her professional career. Coding standards are not the syntax that strictly needs to be followed, they are more of coding conventions that if followed by the programmer can help them to enhance their coding style. The same applies to the case of WordPress where it has its own coding standards which every developer should have the knowledge of. Taking this into consideration, we have developed a two-part series on WordPress Coding Standards which will help you to know the coding standards for PHP, HTML, CSS, & JS. Here’s how we will progress right through the WordPress Coding Standards series:
  • 2. Part 1: In-Depth Guide On WordPress Coding Standards For PHP & HTML Part 2: In-Depth Guide On WordPress Coding Standards For CSS & JS In this blog, we will focus on part 1 - WordPress Coding Standards For PHP & HTML and in the next blog, we will focus on part 2 - WordPress Coding Standards For CSS & JS. Before going to into the details of WordPress Coding Standards, you need to know the purpose of the coding standards & why you need to have coding standards. What Is The Purpose Of WordPress Coding Standards? The sole purpose of the WordPress Coding Standards is to create a base for collaboration and review within the various aspects of WordPress open-source project & community right from the core part to the themes and plugins. Why You Need Coding Standards? Coding standards help you to avoid common errors, simplify the modification process & most importantly assists you in improving the readability of your code. In addition to all these, the coding standards ensure that all files within one project appear as if they’re created by a single person. Another major advantage you get by following the coding standards is that anyone will be able to understand your code and also modify it, without contacting you. So, if you’re planning to develop a website in WordPress, you should know the coding standards. Now, let’s dive deep into the core part & understand the various coding standards.
  • 3. Part 1: In-Depth Guide On WordPress Coding Standards For PHP & HTML:- WordPress Coding Standards For PHP 1. Using Single & Double Quotes If you’re someone who is working in a Custom WordPress Development Company, then you must be knowing that appropriate use of single and double quotes is necessary. As per the standard convention if you’re not evaluating anything in the string, then you should use the single quotes. Otherwise, you should always prefer using the double quotes for the string value while writing PHP code for the WordPress platform. Example: echo '<a href="www.url.com" title="Contact">Contact Us</a>'; echo "<a href='$cta_link' title='$cta_title'>$cta_label</a>"; Here, we have used double quotes for displaying the “Contact” as it is a value for the title attribute, while we have used a single quote for ‘$cta_title’ as we’re not evaluating its value. 2. Indentation Another very important thing that you need to remember while writing the code in PHP is the proper use of indentation. The reason behind that is, it always reflects the logical structure of your code. Always use tabs for indentation instead of space, as it improves readability. However, there is one exception: If you've got a block of code which looks more readable if the code is written in an aligned manner, then you can use space for that purpose. Example: [tab]'demo' => 'demovalue'; [tab]'demo1' => 'demovalue1’; [tab]'demo2' => 'demovalue2'; [tab]'demo3' => 'demovalue3'; For associative arrays, each item should start on a new line when the array contains more than one item:
  • 4. Example: $key_value_array = array( [tab]'demo' => 'demovalue', [tab]'demo1' => 'demovalue1', [tab]'demo2' => 'demovalue2', [tab]'demo3' => 'demovalue3', ); Here, you may have noted a comma after the last item. This is recommended by the WordPress as it makes it easier for you to change the order of an array. Example: [tab]'demo3' => 'demovalue3', [tab]'demo1' => 'demovalue1', [tab]'demo' => 'demovalue', [tab]'demo2' => 'demovalue2', ); For the switch structures, the case should be indented one tab from the switch statement and break should be one tab from the case statement. Example: switch ( $condition ) { [tab]case 'value': [tab][tab]demo_function(); [tab][tab]break; [tab]case 'value2': [tab][tab]demo_function1(); [tab][tab]break; } As a thumb rule, Tabs should be used at the beginning of the line for indentation and Space should be used for the mid-line alignment. 3. Brace Style Braces should be used for all the blocks as shown in the snippet below: Example:
  • 5. if ( condition ) { function(); function2(); } elseif ( condition2 && condition3 ) { function3(); function4(); } else { defaul_function(); } In case, you have a really long block, it can be broken into 2 or more shorter blocks to reduce complexity and improve readability. Example: if ( condition ) { function(); function2(); } elseif ( condition2 && condition3 ) { function3(); function4(); } else { defaul_function(); } foreach ( $data as $data_key => $data_value ) { echo $data_value; } One thing that should be noted here is that the use of braces is to avoid single-statement inline control structures. You’re free to use the alternative syntax for control structure, especially when the PHP code is embedded into the HTML. Example: <?php if ( !empty( $data ) ) { ?> <div class="test"> <?php foreach ( $data as $data_key => $data_value ) { ?> <div id="data-<?php echo $data_key; ?>"> <!-- Other Content --> </div> <?php } ?> </div> <?php } ?>
  • 6. 4. Use elseif, Not else if else if is not compatible with the colon-based syntax for if|elseif blocks. Therefore, you should always use elseif instead of using else if. 5. Multiline Function Calls As a WordPress developer, when you split the function call over the multiple lines, always remember to keep each parameter on a separate line. Each parameter should not consume more than one line and multiline parameter values must be assigned to a variable, so you just need to pass that variable to the function call. Example: ``` $bar = array( 'use_this' => true, 'meta_key' => 'field_name', ); $baz = sprintf( /* translators: %s: Friend's name */ esc_html__( 'Hello, %s!', 'yourtextdomain' ), $friend_name ); $a = foo( $bar, $baz, /* translators: %s: cat */ sprintf( __( 'The best pet is a %s.' ), 'cat' ) ); 6. Regular Expressions Always use Perl compatible regular expressions (PCRE) with the reference to their POSIX counterparts. Never use the /e switch, use preg_replace_callback instead. In addition to all these, you should always use single-quoted strings for the regular expressions. 7. Opening & Closing PHP Tags When you’re embedding multiline PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.
  • 7. Example: (multiline) function test_function() { ?> <div> <?php echo '<a href="www.url.com" title="Contact">Contact Us</a>'; ?> </div> <?php } Example: (single line) <input type="text" name="<?php echo $name ; ?>" /> 8. No Shorthand PHP Tags Never use shorthand PHP tags, always use full PHP tags. Example: (Incorrect) ``` <? ... ?> <?= $var ?> Example: (Correct) ``` <?php ... ?> <?php echo $var; ?> 9. Remove Trailing Spaces Always remember to remove the trailing whitespaces at the end of your each coding line. You should omit the PHP tag at the end of the file. However, if you’re using the tag, then don’t forget to remove the trailing whitespace. 10. Proper Usage Of Space Always put space after every comma and also on both sides of logical, comparison, string and assignment operators. Example:
  • 8. y == 2 foo && bar ! foo array( 1, 2, 3 ) $baz . '-4' $term .= 'Z' Remember to put spaces on both sides opening and closing parentheses of if, elseif, foreach, for, and switch blocks. Example: ``` foreach ( $foo as $bar ) { … Also, follow this rule while defining a function. Example: function dummy( $param1 = 'foo', $param2 = 'bar' ) { ... function my_dummy_function1() { ... When you’re calling any function, you need to follow the rule mentioned above. Example: first_function1( $param1, func_param( $param2 ) ); my_dummy_function(); For logical comparisons, the same rule applies. Example: ``` if ( ! $foo ) { ... When you’re performing typecasting, the above rule is also valid. Example: ``` foreach ( (array) $foo as $bar ) { ...
  • 9. $foo = (boolean) $bar; When referring to array items, include a space around the index only if it’s variable. Example: $x = $foo['bar']; // correct $x = $foo[ 'bar' ]; // incorrect $x = $foo[0]; // correct $x = $foo[ 0 ]; // incorrect $x = $foo[ $bar ]; // correct $x = $foo[$bar]; // incorrect For a switch block, there should be any space before the colon for a case statement. Example: ``` switch ( $foo ) { case 'bar': // correct case 'ba' : // incorrect } Similarly, there should be no space before the colon on the return type declaration. Example: ``` function sum( $a, $b ): float { return $a + $b; } 11. Formatting SQL Statements When you’re formatting any SQL statement, you should break it into several lines and indent if it’s sufficiently complex. Always capitalize the SQL parts of the statements such as WHERE or UPDATE. Functions that update the database should expect their parameters to lack SQL slash escaping when passed. For that purpose, escaping should be done by using $wpdb->prepare(). $wpdb->prepare() is a method that handles escaping, quoting and int-casting for SQL queries.
  • 10. Example: <?php // set the meta_key to the appropriate custom field meta key $meta_key = 'miles'; $allmiles = $wpdb->get_var( $wpdb->prepare( " SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s ", $meta_key ) ); echo "<p>Total miles is {$allmiles}</p>"; ?> Here, %s is used for string placeholders and %d is used for integer placeholders. Note that they are not ‘quoted’! $wpdb->prepare() will take care of escaping and quoting for us. This is the benefit you get if you utilize this function. 12. Database Queries Always avoid touching the database in a direct manner. Utilize the functions for extracting the data whenever possible. The reason behind that is, Database Abstraction (using functions in place of queries) helps you to keep your code forward-compatible. 13. Naming Conventions Always use lowercase for a variable, action/filter, and function names. Separate the words by using underscore. In addition to that, choose a name which is unambiguous & self-documenting. Example: function some_name( $some_variable ) { [...] } For class name, you should use capitalize words which are separated by underscores. Example: ``` class Walk_Categorization extends Walk { [...] } All the constants should be in upper-case with words being separated by underscores.
  • 11. Example: ``` define( 'PI', true ); The file should be named descriptively by using the lowercase and for separating the words you should utilize hyphen. My-new-theme.php For class file name should be based on the class name i.e. class- followed by a hyphen. Example: If the class name is class Walk_Categorization, then the class file name should be class-walk-categroization.php There is one exception in the class file name for three files: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. These files are ported into Backpress and therefore, they are prepended with class. instead of a hyphen. 14. Self-Explanatory Flag Values for Function Arguments Always prefer using true & false for the string values when you're calling a function. Example: // Incorrect function eat( $what, $slowly = true ) { ... } eat( 'wheat', true ); eat( 'rice', false ); Now, PHP doesn’t support flag arguments and therefore, sometimes the values of flags are meaningless as it is in our example shown above. So, for that type of scenario, you should make your code readable by utilizing descriptive string values instead of booleans. Example: // Correct function eat( $what, $slowly = ‘slowly’) { ... }
  • 12. eat( 'wheat', ‘slowly’ ); eat( 'rice', ‘quickly’ ); 15. Interpolation for Naming Dynamic Hooks For naming the dynamic hooks, you should utilize the interpolation methodology rather than using the concatenation for readability purpose. Dynamic hooks are the one which includes dynamic values in their tag name - {$new_status}_{$post->post_type} (publish_post). Always include the variables of your hook tags inside the curly braces {} and the outer tag name should be wrapped in double quotes. The reason behind following this methodology is to ensure that PHP can correctly parse the variable types with interpolated string: Example: ``` do_action( "{$new_status}_{$post->post_type}", $post->ID, $post ); 16. Ternary Operator For using the ternary operator, always have them test if the statement is true, not false. Otherwise, it can create a massive confusion in the future. Example: ``` $musictype = ( 'jazz' == $music ) ? 'cool' : 'blah'; 17. Yoda Conditions When you’re doing the logical comparisons which include variables, always put the variable on the right-hand side & constants, literals, or function calls on the left-hand side. If neither side has a variable, then the order is not that important. Example: ``` if ( true == $the_force ) { $victorious = you_will( $be ); } Here, if you omit an equals sign (=), then you will get a parse error, as you can’t assign a value to constant like true. Instead of that, if you’ve written ( $the_force = true ), the assignment would be
  • 13. perfect and you won’t get an error. This is known as the Yoda Condition and it applies to ==, !=, ===, !==, <, >, <= or >= operators. 18. Clever Coding For coding, readability is more important than cleverness. Example: ``` isset( $var ) || $var = some_function(); This might look clever, but it has low readability. Instead of that, if you write: if ( ! isset( $var ) ) { $var = some_function(); } Then, the readability improves drastically. In the case of a switch statement, it’s ok to have multiple cases in a common block. However, if a case contains a block, the falls through to the next block, then this should be explicitly commented as shown in the snippet below: switch ( $foo ) { case 'bar': // Correct, an empty case can fall through without comment. case 'baz': echo $foo; // Incorrect, a case with a block must break, return, or have a comment. case 'cat': echo 'mouse'; break; // Correct, a case with a break does not require a comment. case 'dog': echo 'horse'; // no break // Correct, a case can have a comment to explicitly mention the fall-through. case 'fish': echo 'bird'; break; } WordPress Coding Standards For HTML 1. Validation
  • 14. All the HTML pages should be verified with the help of the W3C Validator to ensure that markup is well-formed. Although this is not the only indicator of good coding, it helps to solve the problems that are to be tested via the automation process. The manual code review cannot be as effective as this one and that’s why it is recommended that you should validate your code. 2. Self-Enclosing Elements All tags must be properly closed. Howver, for the tags that are self-enclosing, the forward slash should have once space preceding it. Example: ``` <br /> //Correct <br/> //Incorrect 3. Attributes & Tags All the tags, as well as their attributes, must be written in lowercase. In addition to that, attribute values should be in lowercase when the purpose of the text is just to be interpreted by a machine. However, when an attribute value is going be read by a human, proper capitalization should follow: Example: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> // For Machine <a href="http://abc.com/" title="Content Writer">ABC.com</a> // For Human 4. Quotes As per the W3C specification for XHTML, all the attributes must have a value & must be wrapped inside single or double quotes. Example: ``` <input type="text" name="ABC" disabled="disabled" /> //Correct <input type='text' name=’ABC’ disabled='disabled' /> //Correct <input type=text name=email disabled>//Incorrect
  • 15. Howver, in HTML all attributes do not have to have values & they do not have to be quoted. But you should follow these conventions to avoid any kind of security vulnerabilities. 5. Indentation Like PHP, HTML indentation should always reflect logical structure. So always use tabs and not spaces. If you’re mixing PHP & HTML, then indent PHP blocks to match the HTML code. Example: ?php if ( ! have_posts() ) : ?> <div id="post-1" class="post"> <h1 class="entry-title">Not Found</h1> <div class="entry-content"> <p>Apologies, but no results were found.</p> <?php get_search_form(); ?> </div> </div> <?php endif; ?> Final Thoughts… Every programming language has its own coding standards which need to be followed by the programmer in order to enhance the readability of the code. The same is the case with WordPress, where there are coding standards for PHP, HTML, CSS & JS. Here, we have tried to provide you with an in-depth guide on WordPress Coding Standards For PHP & HTML which will help you in future when you're developing something in WordPress. If you’ve any question or suggestion regarding this subject, then do mention them in our comment section. Thank You! Originally Published at esparkinfo.com