Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Writing Files During WordPress Updates

Plugin and theme updates often need extra work after files are replaced: regenerate a cache, write a manifest, record a migration, or refresh generated metadata. file_put_contents() may work on one server and fail on another because web-process permissions and transports differ. Partial writes can also leave stale output. The WordPress Filesystem API provides a transport-aware layer for direct disk access, SSH2, and FTP-family methods while keeping plugin code aligned with WordPress conventions.

Australian developers encounter this in WooCommerce agencies and small studios serving Sydney, Melbourne, and Brisbane. Updates are commonly scheduled after trading hours, while a window shown in Sydney time can drift against Brisbane when New South Wales enters daylight saving. Generated state should use UTC timestamps and avoid assumptions about the server timezone. The same care applies when a plugin creates indexes, lock files, or configuration exports during an update.

Why use the filesystem abstraction

The API helps because an update is a workflow, not merely a sequence of copy() calls. A plugin may replace code in one directory while writing an artifact elsewhere, and the web server may have different ownership rules for each path. WordPress abstracts those differences behind methods such as put_contents(), move(), mkdir(), delete(), and writable().

The abstraction does not choose a safe directory, validate content, or make every operation transactional. Its methods also return simple success values rather than detailed exceptions, so callers must check them. A dependable design separates path selection and payload creation from the transport-specific write.

Use the API when a file belongs to an administrative update, particularly when a site may use a non-direct transport. Ordinary PHP file functions can be adequate for a one-off action on a local machine. Reusable plugin code should still use the API because the installation may later move to a managed Australian host or a client’s FTP server.

Prepare a reliable update writer

Start with a helper that loads WordPress’s filesystem classes and returns the shared filesystem object. An update request may already have initialised it, so the helper should reuse the global rather than create a competing transport.

defined( 'ABSPATH' ) || exit;

function myplugin_get_filesystem() {
    require_once ABSPATH . 'wp-admin/includes/file.php';

    global $wp_filesystem;

    if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
        WP_Filesystem();
    }

    if ( ! $wp_filesystem instanceof WP_Filesystem_Base ) {
        return new WP_Error(
            'filesystem_unavailable',
            'The WordPress filesystem is unavailable.'
        );
    }

    return $wp_filesystem;
}

The helper deliberately avoids requesting passwords. An unattended update callback should fail safely if its transport was not established, rather than display an interactive credentials form. A separate administrative workflow can collect credentials with request_filesystem_credentials() and initialise the required method.

Choose a storage location before opening the transport. Generated state usually belongs under wp-content/uploads, not inside the plugin folder that another update may overwrite. This also avoids placing new executable files in the site’s PHP execution path. Confirm that the parent is writable and create a dedicated child directory with restrictive permissions.

Run writers after plugin updates

The upgrader_process_complete action provides a suitable point after a successful plugin update. This example stages a JSON file, checks each return value, and records only version and timing data:

add_action( 'upgrader_process_complete', 'myplugin_after_update', 10, 2 );

function myplugin_after_update( $upgrader, $hook_extra ) {
    if ( 'plugin' !== ( $hook_extra['type'] ?? '' ) ) {
        return;
    }

    if ( 'update' !== ( $hook_extra['action'] ?? '' ) ) {
        return;
    }

    $plugin_file = $hook_extra['plugin'] ?? '';

    if ( 'my-plugin/my-plugin.php' !== $plugin_file ) {
        return;
    }

    require_once ABSPATH . 'wp-admin/includes/plugin.php';

    $plugin_data = get_plugin_data(
        WP_PLUGIN_DIR . '/' . $plugin_file,
        false,
        false
    );

    $result = myplugin_write_update_state(
        array(
            'version'        => $plugin_data['Version'] ?? 'unknown',
            'updated_at_utc' => gmdate( 'c' ),
        )
    );

    if ( is_wp_error( $result ) ) {
        update_option( 'myplugin_update_error', $result->get_error_message(), false );
        return;
    }

    delete_option( 'myplugin_update_error' );
}

function myplugin_write_update_state( array $payload ) {
    $filesystem = myplugin_get_filesystem();

    if ( is_wp_error( $filesystem ) ) {
        return $filesystem;
    }

    $uploads = wp_upload_dir();

    if ( ! empty( $uploads['error'] ) ) {
        return new WP_Error( 'uploads_unavailable', $uploads['error'] );
    }

    $directory = trailingslashit( $uploads['basedir'] ) . 'my-plugin-state';

    if ( ! $filesystem->is_dir( $directory )
        && ! $filesystem->mkdir( $directory, FS_CHMOD_DIR ) ) {
        return new WP_Error(
            'state_directory_failed',
            'Could not create the state directory.'
        );
    }

    $target    = trailingslashit( $directory ) . 'update.json';
    $temporary = $target . '.' . wp_generate_uuid4() . '.tmp';
    $json      = wp_json_encode(
        $payload,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
    );

    if ( false === $json ) {
        return new WP_Error(
            'state_encode_failed',
            'Could not encode the update state.'
        );
    }

    if ( ! $filesystem->put_contents( $temporary, $json . PHP_EOL, FS_CHMOD_FILE ) ) {
        $filesystem->delete( $temporary );

        return new WP_Error(
            'state_write_failed',
            'Could not write the update state.'
        );
    }

    if ( ! $filesystem->move( $temporary, $target, true ) ) {
        $filesystem->delete( $temporary );

        return new WP_Error(
            'state_move_failed',
            'Could not replace the update state.'
        );
    }

    return $target;
}

The temporary file reduces the chance that readers will encounter a partially written JSON document. It is not a universal atomicity guarantee because transport implementations differ, so consumers should tolerate a missing or invalid file and recover from known data. The callback is also idempotent: running it again replaces the marker rather than appending to it.

Plugins that ship generated block metadata should treat that metadata as build output. The registration steps in ACF block registration show the WordPress side of that workflow. After changing registered block data, regenerate the relevant file with the staged writer instead of editing the installed plugin directory manually.

Handle credentials and transfer methods

The direct method is common on Australian hosts with local disks, including managed platforms serving Sydney and Melbourne customers. It uses the PHP process account, so a path that is writable during deployment may still be unwritable for the web user. Test both identities when a client operates a local server.

SSH2 and FTP-family transports behave differently. They require credentials, may expose passwords to the WordPress process, and can fail because of passive-mode settings, TLS rules, or directory permissions. request_filesystem_credentials() can collect these details on an interactive administrator screen, after which WP_Filesystem() initialises the selected method.

Do not call a credential prompt from cron, an unattended deployment, or the update callback shown earlier. Establish the transport through a secure administrative workflow, or use direct access where the hosting architecture permits it. Never save FTP or SSH passwords in wp_options, generated JSON, or routine logs. Plain FTP also lacks transport encryption, so Australian clients handling customer data should prefer SSH2 or a properly configured encrypted connection.

Secure paths, permissions, and stored data

Build paths from a trusted base and a fixed filename. Do not concatenate a request parameter into a directory name, and reject relative segments such as ... If user input is unavoidable, sanitise it with WordPress functions, resolve the final path, and verify that it remains beneath the intended upload directory. Apply restrictive file and directory modes rather than granting world-writable permissions.

The payload should contain the minimum useful data. A WooCommerce store in Melbourne or Brisbane might produce an export containing customer names, addresses, emails, or order histories. Where the Privacy Act 1988 applies, personal information must be handled consistently with the Australian Privacy Principles, including its collection, storage, use, disclosure, and security. The Spam Act 2003 also matters when customer email data feeds commercial messages. Generated update files should normally hold identifiers, counts, versions, and timestamps rather than personal records.

Keep secrets out of files that a web server can request. If a generated file contains an API key, store it outside the public document root with server-level restrictions, or use a secret-management service. Australian Consumer Law requirements also make dependable pricing, product availability, and order records important for online sellers, so generated caches should never become the only authoritative source. Redact sensitive values from error messages and support logs.

Test and compare update transports

Test the complete transition from an old plugin version to a new one in a staging copy. Exercise a fresh update, a repeated update, a failed write, and recovery after a temporary file is left behind. Confirm that the callback targets only the intended plugin; bulk plugin updates supply different hook data and need their own filtering logic.

Observe return values and retain a small diagnostic record. A sanitised event log can show the plugin version, transport method, target path, timestamp, and error code without exposing credentials or customer data. Provide a safe retry path rather than deleting known-good state after a partial failure.

Compare the transport behaviour that matters during real maintenance windows:

Check Direct filesystem SSH2 FTP-family transport
Setup Uses the PHP process account Requires an SSH connection Requires host, account, and transfer configuration
Common failure Ownership or permission mismatch Authentication, key, or network timeout Passive mode, TLS, or directory permission failure
Write verification Check put_contents() and move() Check both returns and remote permissions Check both returns and remote permissions
Operational choice Simple for local-disk hosting Good for remote managed servers Use only when client infrastructure requires it
Main caution Identity may differ from deployment user Credentials must stay out of files Plain FTP can expose credentials and data