WordPress Coding Standards

Why code formatting matters: A few reasons to pay attention to the format of your code.

  • Readability – Properly formatted code is easier to read and understand for both developers and collaborators.
  • Maintainability – Well-formatted code is more maintainable. When developers need to make changes or debug code, clear formatting makes it quicker to navigate and modify. This reduces the risk of introducing bugs during maintenance.
  • Collaboration – In collaborative projects, consistent code formatting ensures that team members can seamlessly work together. It promotes uniformity across the codebase, making it easier for developers to review each other’s contributions and understand the overall project structure.
  • Debugging – Properly formatted code aids in debugging efforts. Clean and organized code can help pinpoint issues more efficiently.
  • Scalability – As projects grow in size and complexity, maintaining a consistent code format becomes increasingly important.
  • Code Reviews – During code reviews, adherence to formatting standards ensures that reviewers can focus on the code’s functionality and logic rather than getting distracted by formatting inconsistencies.

PHP IN WORDPRESS

-Line breaks

  • WordPress’ documentation says nothing in particular about line breaks, but adding a line break after most statements is common practice. Variable definitions, if blocks, array items, and so on should be on separate lines.

$my_value = 'Me';
$your_value = 'You';
$their_value = 'Them';
if ( $my_value == 'You' ) {
 echo 'It seems like you are mixed up with me';
}

-Space usage

  • Remove all trailing spaces from line endings, including empty lines with tabbed or non-breaking spaces. However, ensure that spaces are used within parentheses to enhance code readability.

$number = (integer) $_GET['number'];
if ( $number === 4 ) {
 echo 'You asked for a four!';
}

-Indentation

  • Indent code to show a logical structure. The goal here is readability, so any indentation that makes the code more readable is a good practice. Use tabs at the beginning of lines, and use spaces for mid-line indentation.

$arguments = array(
 'mythoughts' => array(
 'guitars' => 'I love guitars',
 'applepie' => 'Apple Pie is awesome'
 ),
 'yourthoughts' => array(
 'guitars' => 'Meh',
 'applepie' => 'Love it!'
 )
);
if ( have_posts() ) {
 while ( have_posts() ) {
 get_template_part( 'template', 'blogpost' );
 }
}

-File Header

  • The file header DocBlock is used to give an overview of what is contained in the file.

-Braces

  • The main rule in the WordPress Codex is to use single quotes when you are not evaluating anything inside a string. If you need to use quotes inside a string, just alternate.

$name = 'Daniel';
$hello = "My name is '$name'";

-Formatting SQL queries

  • SQL query keywords must be capitalized, and complex queries should be broken into multiple lines.
$simple_query = "SELECT * FROM $wpdb->posts WHERE comment_count > 3 LIMIT 0, 10
$complex_query = "
SELECT * FROM $wpdb->posts WHERE
post_status = publish AND
comment_count > 5 AND
post_type = 'post' AND
ID IN ( SELECT object_id FROM $wpdb->term_relationships WHERE
term_taxonomy_id = 4 )
";

-Naming conventions

  • Never use CamelCase for names in WordPress code. Functions may contain only lowercase characters, separated by underscores if needed. Capitalize the first letter of each word in a class name, and separate words with underscores.
  • File names should all be lowercase, with hyphens separating the parts of the name.

Example


$event = new My_Event();
$event->save_event_to_file( 'event-file.txt', 'noformatting' );
$product = new Product_Catalog();
$product->add_product_to_inventory( 'product-details.txt', 'noformat' );
$order = new Order_Processing(); 
$order->process_order( 'order-file.txt', 'pending' ); 
$gallery = new Image_Gallery();
$gallery->upload_image( 'image-file.jpg', 'resize' );

 

  1. Descriptive and Clear Names.
  2. Follow a Standard Format.
  3. Organize Files by Functionality.
  4. Avoid Special Characters or Spaces.
  5. Versioning and Date Information.

-Comparison Statements

  • One great practice, and not just for WordPress, is to always write a variable in a comparison on the right side.
if ( 3 == $my_number ) {
 echo 'BINGO!';
}
if ( 'hello' == $greeting ) {
 echo 'Welcome!';
}
if ( true == $is_logged_in ) {
 echo 'Welcome back!';
}
if ( 'jpg' == $file_extension ) {
 echo 'This is a JPEG file.';
}
if ( null == $user_data ) {
 echo 'No user data found.';
}

-Clear Commenting

  • Proper use of inline commenting.
/**
* Calculates the total amount.
* @param float $subtotal The subtotal amount.
* @param float $tax The tax amount.
* @return float The total amount including tax. 
*/
function calculate_total($subtotal, $tax) {
 return $subtotal + $tax;
}
\

-Avoid Reserved Keywords

  • Avoid using reserved keywords as identifiers for variables, functions, or classes. Doing so prevents conflicts with WordPress core functionality and ensures seamless integration of your code with the broader WordPress ecosystem.
  • WordPress Reserved Keywords – https://codex.wordpress.org/Reserved_Terms

-Convert Big Code in Chunks

  • Break down the large function into smaller chunks so that we can reuse it in other functionalities.

-Multi-Language

  • Text strings should be wrapped in translation functions like _(), e(), or esc_html__(). This allows for easy localization of themes and plugins.

For more reference review “PHP Coding Standards

-Filter & action

  1. Actions: Think of actions as places where you can add extra steps to the WordPress process. For example, you can use an action to add a custom message at the end of each post or add a widget in the sidebar. Actions let you add new elements or run specific code at different points on your site.
    add_action('wp_footer', function() 
    echo '<p>Thank you for visiting our site!</p>';
     });

    Explanation: This code adds a custom thank-you message to your site footer on every page without changing the footer file directly.

  2. Filters: Filters are used to change existing content or data before it’s shown on your site. For example, you might use a filter to add custom text at the end of each post or change how a title is displayed. Filters let you take something WordPress is about to show and adjust it.
    add_filter('the_title', function($title) {
    return $title . ' - My Blog';
    });

    Explanation: This code takes each post title and adds “- My Blog” at the end.

    In Summary

    • Actions let you add new things at specific points (like footers or headers).
    • Filters let you change existing data (like titles or content).

-File folder creation

  • File and Folder Naming Conventions
    • Use lowercase letters and separate words with hyphens (e.g., custom-functions.php, my-plugin-folder).
    • Avoid spaces, special characters, or underscores in names.
    • Keep names descriptive but concise.
      Examples:

      • Good: custom-styles.css
      • Bad: Custom_Styles.CSS
  • Folder Structure for Custom Development
  • Custom Themes
    • All custom themes should reside in the /wp-content/themes/ directory.
  • Custom Plugins
    • All custom plugins should reside in the /wp-content/plugins/ directory.
/wp-content/plugins//
 ├── assets/
 │ ├── css/
 │ ├── js/
 │ ├── images/
 └── includes/
 └── core-functions.php
 ├── .php
 └── README.md
  • Standard Practices for Custom Files
    • Custom Scripts and Styles: Store in the /assets/css/ and /assets/js/ folders under themes or plugins.
    • Template Parts: Use the /template-parts/ directory to organize reusable template files in themes.
    • Includes: Use the /inc/ or /includes/ directory for custom PHP files that include additional functionality.
  • Security Considerations
    • Use .htaccess files in directories like /wp-content/uploads/ to restrict direct access to sensitive files. sensitive files.Display Example Code
      
      # Prevent PHP execution
      <Files *.php>
       deny from all
      </Files>
       

-Basic PHP rules

1) PHP Syntax:

>> Every PHP statement should end with a semicolon (;).
echo 'Hello, world!';

 

2) PHP Tags:

>> PHP code is enclosed in <?php and ?>.
<?php
echo 'Hello, world!';
?>

 

3) Data Types:

>> PHP supports several data types including strings, integers, floats, booleans, arrays, and objects.
$integer = 10; // Integer
$float = 10.5; // Float
$string = "Hello"; // String
$boolean = true; // Boolean

 

4) Comments:

>> PHP supports single-line comments (// or #) and multi-line comments (/* */).
// This is a single-line comment
# This is also a single-line comment
/* This is a
 multi-line comment */

 

5) String Concatenation:

>> Use a period (.) to concatenate strings in PHP.
$greeting = 'Hello';
$name = 'World';
echo $greeting . ' ' . $name; // Outputs 'Hello World'

 

6) PHP Constants:

>> Constants are defined using the define() function and cannot be changed once set.
define('PI', 3.14);
echo PI; // Outputs '3.14'

 

7) Arrays:

>> PHP arrays can be indexed or associative (key-value pairs).
// Indexed Array
$colors = array('Red', 'Green', 'Blue');
echo $colors[0]; // Outputs 'Red'
// Associative Array
$person = array('name' => 'John', 'age' => 30);
echo $person['name']; // Outputs 'John'

 

8) Control Structures:

>> PHP uses common control structures like if, else, while, for, foreach, switch.
$age = 20;
if ($age >= 18) {
 echo 'Adult';
} else {
 echo 'Minor';
}
$day = 2;
switch ($day) {
 case 1:
 echo 'Monday';
 break;
 case 2:
 echo 'Tuesday';
 break;
 default:
 echo 'Other day';
}

 

9) Loops:

>> PHP supports for, while, and foreach loops.
for ($i = 1; $i <= 5; $i++) {
 echo $i . ' ';
}
$fruits = array('Apple', 'Banana', 'Cherry');
foreach ($fruits as $fruit) {
 echo $fruit . ' ';
}

 

10) Functions:

function greet($name) {
 return 'Hello, ' . $name;
}
echo greet('John'); // Outputs 'Hello, John'

 

11) Superglobals:

>> PHP provides several superglobal variables, such as $_GET, $_POST, $_SESSION, and $_COOKIE, which are used to access form data, session data, etc.
// URL: index.php?name=John
echo $_GET['name']; // Outputs 'John'
// HTML form:
// <form method="post">
// <input type="text" name="name">
// <input type="submit" value="Submit">
// </form>
echo $_POST['name']; // Outputs the value submitted in the form

 

12) File Inclusion:

>> PHP allows you to include external files using include or require.
include('header.php'); // Includes header.php file
require('footer.php'); // Requires footer.php file

 

13) Error Handling:

>> Use try and catch for exception handling.
try {
 // Code that may throw an exception
 throw new Exception("An error occurred");
} catch (Exception $e) {
 echo 'Caught exception: ', $e->getMessage();
}

 

14) Global Variables:

>> To access global variables inside a function, use the global keyword or the $GLOBALS array.
$x = 10;
function test() {
 global $x;
 echo $x; // Outputs '10'
}
test();

 

15) PHP Sessions:

>> PHP sessions allow you to store user data across multiple pages.
session_start();
$_SESSION['username'] = 'john_doe';
echo $_SESSION['username']; // Outputs 'john_doe'

 

16) PHP Include Path:

>> The include path is a list of directories that PHP searches for files to include.
set_include_path('/path/to/directory');
include('myfile.php'); // PHP will search the set include path

Security

Your product should take advantage of all of the security features of WordPress. This includes (but is not limited to) the following:

    1. Use nonces to verify user identity.
    2. Sanitize and validate user input.
    3. Escaping Output
    4. Use the Default WordPress function.
  • Update Plugins Regularly bases.
    • Limit User Permissions.
  • SMTP set up
    • Third-Party Libraries and Dependencies

More Infohttps://developer.wordpress.org/apis/security/

How to Test for Compliance with WordPress Coding Standards?

WordPress standards are essential for performance and maintainability. Compliance testing ensures that your code meets established guidelines systematically.

  1. PHP CodeSniffer Integration
  2. Unit Testing for Functionality
  3. Generate Log File.

Visual Studio Extensions

  1. Auto Close Tag
  2. Auto Rename Tag
  3. Format HTML in PHP
  4. GitLens
  5. PHP Intellisense
  6. PHP DocBlocker
  7. Intelephense
  8. PHP_CodeSniffer
  9. phpcbf
  10. phpcs
  11. WordPress Snippets

WordPress Coding Standards Checklist

Priority 1: General Best Practices

  1. Readability and Maintainability
    • Format code for readability and clear structure.
    • Use consistent indentation: tabs for line start, spaces mid-line.
    • Add line breaks after most statements for better clarity.
  2. Naming Conventions
    • Use lowercase names with underscores for functions.
    • Capitalize class names with underscores separating words.
    • Use descriptive, concise file and folder names with hyphens.
    • Avoid CamelCase, special characters, or spaces in names.
  3. Clear Commenting
    • Add inline comments for necessary context.
    • Use DocBlocks to describe function parameters and return values.
  4. Comparison Statements
    • Place variables on the right side for clarity (e.g., if (3 == $my_number)).
  5. Avoid Reserved Keywords
    • Do not use WordPress reserved terms for identifiers.

Priority 2: WordPress-Specific Coding Standards

  1. Quotes
    • Use single quotes (') unless interpolation or special characters require double quotes (").
  2. Braces
    • Always use braces {} for clarity, even for single-line blocks.
  3. Filters and Actions
    • Implement add_action and add_filter for extensibility.
    • Use actions to add new features and filters to modify existing data.
  4. File Header
    • Include a DocBlock at the top of files summarizing their purpose.

Priority 3: Structuring and Organizing Code

  1. Folder and File Organization
    • Store custom themes in /wp-content/themes/.
    • Store custom plugins in /wp-content/plugins/<plugin-name>/.
    • Use /assets/css/ and /assets/js/ for custom styles and scripts.
    • Use /template-parts/ for reusable templates.
    • Use /inc/ or /includes/ for additional PHP functionality.
  2. Formatting SQL Queries
    • Capitalize SQL keywords for readability.
    • Break complex queries into multiple lines.
  3. Descriptive Names
    • Use clear, meaningful names for variables, functions, and classes.
  4. Multi-Language Support
    • Wrap text strings in translation functions: __(), _e(), or esc_html__().

Priority 4: Security and Error Handling

  1. Security Considerations
    • Use .htaccess to restrict direct access to sensitive files.
    • Prevent PHP execution in /wp-content/uploads/.
  2. Error Handling
    • Use try and catch blocks for exceptions.

Priority 5: PHP Basics

  1. Basic Syntax
    • End every statement with a semicolon.
    • Enclose PHP code in <?php and ?>.
  2. Data Types
    • Use appropriate data types: strings, integers, floats, booleans, arrays, objects.
  3. String Concatenation
    • Use the period (.) operator for concatenating strings.
  4. Control Structures and Loops
    • Use if, else, switch, while, for, and foreach for flow control.
  5. Functions
    • Write reusable functions with clear naming and parameters.
  6. Superglobals
    • Access form data with $_GET or $_POST.
    • Use $_SESSION for session data.
  7. File Inclusion
    • Use include or require to modularize code.
  8. PHP Constants
    • Use define() to create constants.
  9. Global Variables
    • Use global or $GLOBALS to access variables across scopes.
  10. PHP Sessions
    • Start sessions with session_start() and store user data in $_SESSION.
  11. Chunk Large Code
    • Break large functions into smaller, reusable chunks for better readability.
  12. PHP Include Path
    • Set include paths for reusable file access.