How to Protect Project's Budget With WordPress Coding Standards?

Article discusses the importance of WordPress Coding Standards as the solution to prevent problems that can make your business lose real money.

What has a bigger impact on a project's success - the code that meets the visual rules or a system crashing from heavy WP_Queries? Most developers would likely prioritize performance, as system failures can be far more damaging for the brand reputation or client's experience.

The way the code looks like certainly affects the final results, but is is not as significant as issues that prevent users from using the platform. Some businesses lose significant revenue for every minute their website is down, so as developers, it's our responsibility to do everything we can to prevent this, just as we write the code.

In my first video about WordPress Coding Standards, I focused too much on the visual side of the code - preferences that might differ from person to person. But WordPress Coding Standards are much more than just a code style: they are also about ensuring performance, security, and system compatibility. That’s what I want to highlight today.


How to Improve System Performance With WordPress Coding Standards?

What's the easiest way to break WordPress with huge traffic? Performing a WP_Query fetching a huge number of posts with meta query. This is a common issue made by WordPress developers that can affects the system. It's easy to make such shortcuts when „we only have 10 posts - however, when the system grows, these queries can became hard to handle.

function get(): array
{
    return get_posts(
        [
            'post_type' => 'post',
            'posts_per_page' => 200,
            'meta_query' => [
                [
                    'key' => 'color',
                    'compare' => '=',
                    'value' => 'red',
                ],
            ],
        ]
    );
}

How do WordPress Coding Standards help here? WordPress Coding Standards mark the usage of huge posts_per_page argument or usage of meta_query arguments as WARNING immediately indicating the part of the code that requires special attention.

You might argue that it's just a warning, but our team follows a strict 'no error, no warning' policy. If the code generates a warning, it's a clear sign that something isn’t right. Any such issue must have a valid justification; otherwise, the code won’t be accepted in the PR.

In this case, we can use other, more effective pagination methods, modify the query to return a manageable number of elements, or reevaluate our business requirements. There are many alternatives to using this kind of shortcut so it's good to know them.


How to Improve System Security With WordPress Coding Standards?

What comes to mind first when considering WordPress security and a form that processes user input? Data sanitization should be at the top of your list. It's a critical step that's often overlooked, especially by those just starting with WordPress. Every piece of data that is taken from the user should be filtered and cleaned to prevent security issues ⚠️

add_action('wp_ajax_fm_ajax_handler', function() {
    wp_send_json_success(
        handle([
            'after' => ! empty($_POST['after']) ? $_POST['after'] : 0,
        ])
    );
})

Let's assume that the handle function involves making database queries and requires the after value to be a number. Simply assuming that users will input a number when they see a field with a number type in a form will lead to security risks. It's crucial to assume that users might attempt to enter various other inputs, such as an SQL query that could potentially expose your data. How do WordPress Coding Standards help preventing security breaches?

When data is collected from users, it is flagged as an error if it's not cleaned. While there might be rare cases where data doesn't need sanitization, these are extremely uncommon. In nearly all scenarios, developers should pause and ensure appropriate data sanitization is in place to maintain security and functionality. In this case, we can just cast a value.

add_action('wp_ajax_fm_ajax_handler', function() {
    $nonce = ! empty($_POST['nonce']) ? sanitize_key($_POST['nonce']) : '';

    if (! wp_verify_nonce($nonce, 'nonce')) {
        wp_send_json_error();
    }

    wp_send_json_success(
        handle([
            'after' => ! empty($_POST['after']) ? (int) $_POST['after'] : 0,
        ])
    );
})

How to Improve System Compatibility With WordPress Coding Standards?

WordPress developers often rely on knowledge shared by the community, but keeping up with all the new recommendations can be challenging and time consuming. To illustrate this, consider an example of function that removes file from the server with unlink method.

function delete(string $path): void
{
    if (current_user_can('manage_options')) {
        unlink($path);
    }
}

To standardize file management in the codebase and give developers more control over this aspect, WordPress core suggests using wp_delete_file instead.

It's sometimes hard to keep track of the recommendations like this, however the WordPress Coding Standard can track them for us. WordPress Coding Standards helps by flagging specific solutions as deprecated or not recommended and suggests different ones, letting the developers create a code that is more compatible with the official WordPress rules.

function delete(string $path): void
{
    if (current_user_can('manage_options')) {
        wp_delete_file($path);
    }
}

How to Install WordPress Coding Standards?

If you plan to use WordPress Coding Standards, you need to install them first, since they are not available by default in PHP Code Sniffer. You can do it with Composer.

composer require wp-coding-standards/wpcs:"^3.0" --dev

Then in the phpcs.xml.dist configuration and change the standard from PSR12 to WordPress.

<?xml version="1.0"?>

<ruleset name="pragmatedev">
  <arg name="colors" />
  <arg value="s" />

  <file>app</file>
  <file>functions.php</file>

  <rule ref="WordPress" />
</ruleset>

Those are just three examples of how WordPress Coding Standards can improve codebase, but they offer much more. For instance, they can flag missing nonce verifications when processing user input in forms - something often overlooked, or also warn against making direct database queries using the $wp_db object.

They for sure provide much more than what’s covered in the official documentation. In my opinion, the documentation mainly focuses on visual aspects - which is why I initially overlooked other important elements and stated that I don't use them.

Luckily, that’s no longer the case. Me, and my team now use WordPress Coding Standards with some tweaks - mainly for visual consistency since I still choose to use PSR12 as a coding styleHere you can find my phpcs config which yo ucan use in your projects.


What are your thoughts? Like me, did you initially think WordPress Coding Standards were only about visuals? What are the things that you were surprised about? Let me know in the comments and share your experience with others!

avatar

Looking For a Developer Who
Truly Cares About Your Business?

My team and I provide expert consultations, top-notch coding, and comprehensive audits to elevate your success.

Feedback

How satisfied you are after reading this article?