/**
* Send a Slack notification when a post transitions to 'publish' for the first time.
*
* Add your Slack webhook URL to wp-config.php:
* define( 'WPFOLKS_SLACK_WEBHOOK', 'https://hooks.slack.com/services/XXX/YYY/ZZZ' );
*/
add_action( 'transition_post_status', 'wpfolks_notify_slack_on_publish', 10, 3 );
function wpfolks_notify_slack_on_publish( string $new_status, string $old_status, WP_Post $post ): void {
// Only fire when transitioning TO publish FROM a non-publish status
// Prevents firing on every edit of an already-published post
if ( $new_status !== 'publish' || $old_status === 'publish' ) return;
// Only notify for standard posts — adjust post types as needed
if ( ! in_array( $post->post_type, [ 'post', 'project' ], true ) ) return;
// Skip revisions and autosaves
if ( wp_is_post_revision( $post->ID ) || wp_is_post_autosave( $post->ID ) ) return;
if ( ! defined( 'WPFOLKS_SLACK_WEBHOOK' ) || empty( WPFOLKS_SLACK_WEBHOOK ) ) return;
$author = get_the_author_meta( 'display_name', $post->post_author );
$url = get_permalink( $post->ID );
$type = ucfirst( $post->post_type );
$payload = [
'text' => sprintf(
'📝 *New %s Published*: <%s|%s> by %s',
esc_html( $type ),
esc_url( $url ),
esc_html( $post->post_title ),
esc_html( $author )
),
];
wp_remote_post( WPFOLKS_SLACK_WEBHOOK, [
'headers' => [ 'Content-Type' => 'application/json' ],
'body' => wp_json_encode( $payload ),
'blocking' => false, // Non-blocking — doesn't slow down the publish action
'sslverify' => true,
] );
}