Rector: Automated PHP Code Upgrades for WordPress Plugins

Rector is an automated PHP refactoring tool that upgrades your code from one PHP version to another, enforces coding standards, and fixes deprecated API usage — all in a single command. For WordPress plugin developers, it eliminates hours of manual find-and-replace when migrating to PHP 8.x.

Problem: A WordPress plugin codebase written for PHP 7.4 needs to support PHP 8.1+ — updating dozens of deprecated function calls, adding return types, and replacing null-coalescing patterns manually is time-consuming and error-prone.

Solution: Use Rector to automate the upgrade — install it as a dev dependency with composer require --dev rector/rector, configure the PHP version set and WordPress-specific rules in rector.php, then run vendor/bin/rector process src/ in dry-run mode to preview changes before applying them.

The examples below install Rector, configure it for a WordPress plugin project targeting PHP 8.2, run it in dry-run mode to preview changes, and set up a CI step that fails when unprocessed code is detected.

# Install Rector as a dev dependency
composer require rector/rector --dev

# Generate a default config file
vendor/bin/rector init

Configure rector.php for a WordPress plugin:

withPaths([
        __DIR__ . '/src',
        __DIR__ . '/includes',
    ])
    ->withSkip([
        __DIR__ . '/vendor',
        __DIR__ . '/node_modules',
    ])
    // Upgrade to PHP 8.2 syntax
    ->withPhpSets( php82: true )
    // Apply a curated set of safe dead-code removals
    ->withSets([
        SetList::DEAD_CODE,
        SetList::TYPE_DECLARATION,
    ])
    ->withRules([
        AddVoidReturnTypeWhereNoReturnRector::class,
        TypedPropertyFromStrictConstructorRector::class,
    ]);

# Preview changes without writing files (dry run)
vendor/bin/rector process --dry-run

# Apply all changes
vendor/bin/rector process

# Apply to a single file
vendor/bin/rector process includes/class-my-plugin.php

# CI step — fail if any changes are pending (code not yet processed)
# .github/workflows/rector.yml:
# - name: Run Rector
#   run: vendor/bin/rector process --dry-run
#   # Exit code 1 if changes would be made → CI fails

NOTE: Run Rector alongside PHPStan: Rector fixes code, PHPStan validates types. The recommended workflow is: Rector → commit → PHPStan → fix remaining type errors manually. This combination can migrate a medium-size WordPress plugin from PHP 7.4 to PHP 8.2 in under an hour.

Leave Comment

Your email address will not be published. Required fields are marked *