Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 68 · Performance, Tools and Scaling

Testing, Coding Standards and Deployment

Test WordPress code with PHPUnit and wp-env, check style with PHPCS, deploy and move sites safely, keep backups, and translate with __() and _n().

Writing a plugin or theme that works on your laptop is only half the job. Real sites need code that other developers can read, tests that catch regressions, a repeatable way to put changes on a server, backups for the day something goes wrong, and text that can be translated into other languages. This lesson gives you an overview of each of those habits and the tools WordPress developers use for them.

You do not need every tool on every project. A tiny plugin may only need a coding-standards check and a good deployment routine. A plugin sold to thousands of sites should have all of it. Read this lesson as a menu, and pick what fits.

None of the real tooling (PHPUnit with WordPress, wp-env, PHPCS, WP-CLI, Git hosting) runs on this site, so those commands are read-only. The runnable examples are plain-PHP stand-ins: a translation function with plural rules, and a tiny test runner.

Testing WordPress code

Tests are small programs that run your code and check the result. For WordPress there are two useful levels:

  • Unit tests exercise plain PHP functions and classes without loading WordPress at all: a price formatter, a slug generator, a class that parses settings. They are fast. This is the main reason to keep your logic in ordinary classes instead of burying it inside hook callbacks (see plugin structure and OOP).
  • Integration tests load a real WordPress and a test database, so you can create posts, call WP_Query, fire hooks and check what happens. They are slower but test the real behavior.

The classic integration setup uses PHPUnit and the WordPress test library. WP-CLI can scaffold the files:

Terminal
wp scaffold plugin-tests acme-events

That creates a phpunit.xml.dist, a tests/bootstrap.php and an install script that downloads WordPress test files and prepares a throwaway database. A test class then extends WP_UnitTestCase, which gives you factories and resets the database state between tests:

PHP
<?php
class Test_Event_Query extends WP_UnitTestCase {

    public function test_upcoming_events_are_sorted_by_date(): void {
        $late  = self::factory()->post->create( [ 'post_type' => 'event', 'meta_input' => [ '_event_date' => '2031-05-02' ] ] );
        $early = self::factory()->post->create( [ 'post_type' => 'event', 'meta_input' => [ '_event_date' => '2031-04-11' ] ] );

        $ids = wp_list_pluck( acme_get_upcoming_events( '2031-01-01' ), 'ID' );

        $this->assertSame( [ $early, $late ], $ids );
    }
}

You can also test hooks: call do_action() or apply_filters() and assert on the outcome, or use has_action() to check a callback was registered. For code that should not touch WordPress at all, libraries such as Brain Monkey replace WordPress functions with test doubles, which keeps unit tests fast.

wp-env

Setting up PHP, a web server and MySQL for tests is tedious. wp-env (from the @wordpress/env package) runs WordPress in Docker from one small config file in your project:

JSON
{
  "core": null,
  "plugins": [ "." ],
  "themes": [],
  "config": { "WP_DEBUG": true }
}
Terminal
npx wp-env start       # starts a dev site and a tests site
npx wp-env run tests-cli --env-cwd=wp-content/plugins/acme-events vendor/bin/phpunit
npx wp-env stop

"plugins": [ "." ] mounts the current folder as a plugin. Everyone on the team gets the same environment, and a continuous integration server can run the same commands. (For browser-level tests of the block editor, WordPress projects commonly use Playwright, which is beyond this overview.)

A tiny test runner you can run

The idea behind PHPUnit is simple: run functions, compare actual with expected, and report. This stand-in is far smaller than PHPUnit, but the habits are identical: one behavior per test, a clear name, assertSame for strict comparison.

PHP A miniature test runner (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last test fails on purpose, so you can see what a failure report looks like. In a real project a failing test fails the whole build.

Coding standards with PHPCS

WordPress publishes coding standards that describe spacing, naming, Yoda conditions, documentation and security rules. They are enforced by PHP_CodeSniffer (PHPCS) with the WordPress Coding Standards (WPCS) ruleset. Following one style makes core, plugins and your own code read the same way, and the security sniffs flag unescaped output and unchecked nonces (see escaping output and forms and nonces).

Terminal
composer require --dev wp-coding-standards/wpcs dealerdirect/phpcodesniffer-composer-installer

A phpcs.xml.dist file in the project root tells PHPCS what to check:

XML
<?xml version="1.0"?>
<ruleset name="Acme Events">
    <file>.</file>
    <exclude-pattern>/vendor/*</exclude-pattern>
    <exclude-pattern>/node_modules/*</exclude-pattern>

    <rule ref="WordPress-Extra"/>
    <rule ref="WordPress-Docs"/>

    <config name="minimum_wp_version" value="6.4"/>
    <rule ref="WordPress.WP.I18n">
        <properties>
            <property name="text_domain" type="array">
                <element value="acme-events"/>
            </property>
        </properties>
    </rule>
</ruleset>
Terminal
vendor/bin/phpcs          # report problems
vendor/bin/phpcbf         # fix the ones that can be fixed automatically

A few rules you will notice quickly: spaces inside parentheses (if ( $a ) {), array() or short [] arrays (both are allowed in current standards), Yoda conditions (if ( 'yes' === $value )), tabs for indentation and a docblock on every function. Treat the output as advice, not scripture: if you must break a rule on purpose, add a comment such as // phpcs:ignore WordPress.Security.NonceVerification with a reason. Running PHPCS in continuous integration keeps style debates out of code review.

Version control

Put your own code in Git. What exactly goes in the repository depends on what you build:

  • A plugin or theme: the repository root is the plugin or theme folder. Ignore vendor/ and node_modules/ if they are rebuilt during deployment.
  • A whole site: usually only your custom wp-content/themes/my-theme and wp-content/plugins/my-plugin (or a Composer file that installs third-party plugins), not WordPress core.
  • Never commit wp-config.php with real passwords and salts, the uploads folder, caches, or database dumps containing customer data. Keep secrets in environment-specific configuration (see hardening a site).

A simple .gitignore for a site repository:

TEXT
/wp-config.php
/wp-content/uploads/
/wp-content/cache/
/wp-content/upgrade/
/node_modules/

The database is the awkward part: content and settings live in MySQL, not in files. Treat code as the thing you deploy with Git, and move content separately with exports (below). Many teams keep settings in code where possible, for example block theme settings in theme.json and plugin defaults in activation routines.

Deployment and moving a site

A deployment is the repeatable process of getting a tested change onto the live server. A healthy pipeline looks like this:

flowchart LR
    A["Local development"] --> B["Git push"]
    B --> C["CI: PHPCS and tests"]
    C --> D["Deploy to staging"]
    D --> E["Manual check"]
    E --> F["Deploy to production"]
    F --> G["Smoke test and cache purge"]

Every change passes automated checks and a staging copy before it reaches visitors.

Practical rules:

  • Use a staging site, a copy of production on a private URL, and test updates there first.
  • Automate the copy of code (Git pull on the server, rsync, or a CI deploy step) instead of dragging files over FTP.
  • Set the environment type so code can behave differently per environment. Core reads WP_ENVIRONMENT_TYPE (local, development, staging or production) and you can ask with wp_get_environment_type().
  • Purge caches after deploying, and flush rewrite rules only through your activation or upgrade routines (see permalinks and rewrite rules).

To move a site to another host or domain, you need three things: files, database and configuration. With WP-CLI (see WP-CLI) the core of it is:

Terminal
# On the old server
wp db export site.sql
tar czf wp-content.tar.gz wp-content

# On the new server, after uploading both files and creating an empty database
wp config create --dbname=newdb --dbuser=newuser --prompt=dbpass
wp db import site.sql
wp search-replace 'https://old.example.com' 'https://new.example.com' --all-tables --dry-run
wp search-replace 'https://old.example.com' 'https://new.example.com' --all-tables
wp cache flush
wp rewrite flush

Always use wp search-replace (or a tool built on the same idea) for the URL change, never a plain find-and-replace on the SQL file. WordPress stores a lot of data as serialized PHP, where string lengths are part of the format, and a naive edit corrupts it. search-replace understands serialized data. Run it with --dry-run first.

Updates and backups

Outdated plugins are the most common way WordPress sites get hacked, so updating is part of the job. Core installs minor security releases automatically by default; plugins, themes and major releases are a choice you control. A sensible routine:

  1. Back up files and database.
  2. Update on staging and click through the important pages and forms.
  3. Update production, at a quiet time.
  4. Check the site and the PHP error log (see debugging WordPress).

A good backup has these properties: it covers both files and database, it is stored off the server, it runs on a schedule, and you have tested a restore. A backup you have never restored is a hope, not a plan.

Translating with i18n functions

Internationalization (i18n) means writing your code so text can be translated. Wrap every user-facing string in a translation function and give it a text domain, the unique name of your plugin or theme. Translators then provide the translated strings, and WordPress shows the right ones for the site's language. The core functions are:

Function Use
__( 'Text', 'domain' ) Return a translated string
_e( 'Text', 'domain' ) Echo it (no escaping)
esc_html__( 'Text', 'domain' ) Return it escaped for HTML
esc_html_e( 'Text', 'domain' ) Echo it escaped
_x( 'Post', 'verb', 'domain' ) Translate with context, because one English word may need two translations
_n( 'One item', '%s items', $count, 'domain' ) Choose singular or plural form for the number
PHP
<?php
printf(
    /* translators: %s: number of events */
    esc_html( _n( '%s event found', '%s events found', $count, 'acme-events' ) ),
    esc_html( number_format_i18n( $count ) )
);

Four rules keep translations working:

  • The text domain must be a string literal that matches your plugin slug; tools that scan your code cannot read variables.
  • Never build sentences by concatenation. Word order differs between languages, so use placeholders: sprintf( __( '%1$s by %2$s', 'acme' ), $title, $author ), with numbered placeholders so translators may reorder them.
  • Add a /* translators: */ comment above strings with placeholders.
  • Do not call translation functions too early. Wait until the init hook, or later, to be safe; recent WordPress versions load translations on demand and warn when they are requested before init.

WP-CLI can extract the strings into a template file for translators, and later convert their files:

Terminal
wp i18n make-pot . languages/acme-events.pot
wp i18n make-mo languages
wp i18n make-json languages   # for JavaScript translations

Translators fill in a .po file per language, which compiles into a .mo file that WordPress loads. For scripts, use wp_set_script_translations() and the __() from @wordpress/i18n. Plugins hosted on WordPress.org get community translations delivered automatically.

Plural rules

English has two plural forms: one and other. Many languages differ. French treats 0 and 1 as singular. Russian has three forms depending on the last digits. Japanese has just one. Each .po file declares its rule in a Plural-Forms header, and _n() uses it to pick the form. The stand-in below holds some strings in memory and a small plural function per language, so you can see how the same count picks different strings.

PHP __() and _n() with plural rules (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at Russian: 1 and 21 use the first form, 2 and 22 the second, and 0 and 5 the third. A plain "one or many" test would get that wrong, which is why you must always use _n() rather than your own if ( $count === 1 ). French shows that 0 is singular in that language, even though English calls it plural.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why is it useful to keep business logic in plain PHP classes rather than only inside hook callbacks?

    Code that does not depend on WordPress can be tested in milliseconds with PHPUnit alone. Hook callbacks then just call into it.
  2. 2. What does wp-env give a team?

    wp-env starts a development site and a tests site in Docker, so every developer and the CI server run the same setup.
  3. 3. Why should you use wp search-replace instead of a plain text replace when moving a site to a new domain?

    WordPress stores arrays and objects as serialized strings with lengths. Changing a URL by hand breaks those lengths and corrupts the data.
  4. 4. Why must you use _n() instead of checking if the count equals 1 yourself?

    Russian has three forms, Japanese one, and French treats 0 as singular. _n() picks the right form from the language's rule.
  5. 5. Which of these should usually not be committed to the Git repository of a site?

    Secrets and environment-specific settings stay out of version control. Code and tooling configuration belong in it.

Summary

  • Unit tests cover plain PHP logic; integration tests with PHPUnit and the WordPress test library cover real behavior. wp-env gives everyone the same Docker environment.
  • WPCS with PHPCS enforces WordPress style and many security checks; phpcbf fixes what it can.
  • Version control your own code, never secrets or uploads; move content with database exports.
  • Deploy through staging and an automated pipeline, set the environment type and purge caches.
  • Move a site with wp db export, file copy and wp search-replace --dry-run first, never a raw text replace.
  • Update after taking a backup of files and database, stored off the server and restore-tested.
  • Wrap text in __(), _n() and friends with a literal text domain, use placeholders, and let the language's plural rules choose the form.
  • The runnable code is a plain-PHP stand-in, not real WordPress or PHPUnit.

Next: Project: A Block Theme Portfolio