CDN Integration

Using action hooks to integrate Picture Optimizer with CDN and caching systems.

Overview

Picture Optimizer fires WordPress action hooks after image replacement and revert operations. These hooks allow CDN plugins, caching systems, and custom integrations to respond to image changes automatically.

Available Hooks

After Image Replacement

do_action( 'image_forge_after_replace', $attachment_id, $old_url, $new_url, $backup_path );

Parameters:

ParameterTypeDescription
$attachment_idintWordPress attachment post ID
$old_urlstringThe original image URL before replacement
$new_urlstringThe new image URL after replacement
$backup_pathstringRelative path to the backup file in image-forge-originals/

After Image Revert

do_action( 'image_forge_after_revert', $attachment_id, $restored_url );

Parameters:

ParameterTypeDescription
$attachment_idintWordPress attachment post ID
$restored_urlstringThe restored original image URL

Example: CDN Cache Purge

Cloudflare

add_action( 'image_forge_after_replace', function( $attachment_id, $old_url, $new_url, $backup_path ) {
    // Purge both old and new URLs from Cloudflare cache
    $urls_to_purge = array( $old_url, $new_url );

    wp_remote_post( 'https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/purge_cache', array(
        'headers' => array(
            'Authorization' => 'Bearer YOUR_API_TOKEN',
            'Content-Type'  => 'application/json',
        ),
        'body' => json_encode( array( 'files' => $urls_to_purge ) ),
    ) );
}, 10, 4 );

WP Super Cache

add_action( 'image_forge_after_replace', function( $attachment_id, $old_url, $new_url ) {
    if ( function_exists( 'wp_cache_clear_cache' ) ) {
        wp_cache_clear_cache();
    }
}, 10, 3 );

W3 Total Cache

add_action( 'image_forge_after_replace', function( $attachment_id, $old_url, $new_url ) {
    if ( function_exists( 'w3tc_flush_all' ) ) {
        w3tc_flush_all();
    }
}, 10, 3 );

Example: Custom Logging

add_action( 'image_forge_after_replace', function( $attachment_id, $old_url, $new_url, $backup_path ) {
    error_log( sprintf(
        '[Picture Optimizer] Replaced attachment #%d: %s → %s (backup: %s)',
        $attachment_id, $old_url, $new_url, $backup_path
    ) );
}, 10, 4 );

add_action( 'image_forge_after_revert', function( $attachment_id, $restored_url ) {
    error_log( sprintf(
        '[Picture Optimizer] Reverted attachment #%d to: %s',
        $attachment_id, $restored_url
    ) );
}, 10, 2 );

Where to Add Hook Code

Add your hook code to one of these locations:

  • Theme's functions.php — Simple but lost on theme change
  • Custom plugin — Recommended for production
  • Code Snippets plugin — Easy to manage without file editing