Home / Admin / When Update then Slack
Duplicate Snippet

Embed Snippet on Your Site

When Update then Slack

Anytime a plugin or theme or wp updates, it sends an update to slack channel.

Code Preview
php
<?php
// Notify Slack when a plugin, theme, or WordPress core is updated
add_action('upgrader_process_complete', 'notify_slack_updates_v2', 10, 2);
function notify_slack_updates_v2($upgrader_object, $options) {
    $slackURL = "https://hooks.slack.com/services/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"; // Replace with your Slack Webhook URL
    $site_name = get_bloginfo('name');
    // Plugin Updates
    if ($options['type'] === 'plugin' && isset($options['plugins'])) {
        foreach ($options['plugins'] as $plugin) {
            $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
            $message = "The *{$site_name}* has updated the plugin *{$plugin_data['Name']}* to version *{$plugin_data['Version']}*";
            slackAlertForUpdates($slackURL, $message);
        }
    }
    // Theme Updates
    if ($options['type'] === 'theme' && isset($options['themes'])) {
        foreach ($options['themes'] as $theme) {
            $theme_data = wp_get_theme($theme);
            $message = "The *{$site_name}* has updated the theme *{$theme_data->get('Name')}* to version *{$theme_data->get('Version')}*";
            slackAlertForUpdates($slackURL, $message);
        }
    }
    // WordPress Core Updates
    if ($options['type'] === 'core') {
        $wp_version = get_bloginfo('version');
        $message = "The *{$site_name}* has updated WordPress to version *{$wp_version}*";
        slackAlertForUpdates($slackURL, $message);
    }
}
// Function to send Slack alert for updates
function slackAlertForUpdates($slackUrl, $message) {
    $payload = json_encode(['text' => $message]);
    $args = [
        'body' => $payload,
        'headers' => ['Content-Type' => 'application/json'],
        'timeout' => 10
    ];
    $response = wp_remote_post($slackUrl, $args);
    if (is_wp_error($response)) {
        error_log('Slack notification error (Updates): ' . $response->get_error_message());
    } else {
        error_log('Slack notification (Updates) sent successfully');
    }
}

Comments

Add a Comment