Skip to content

Instantly share code, notes, and snippets.

@andreasciamanna
Last active June 17, 2020 12:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasciamanna/d495c8ccdc6a85f94887f9d71fade94b to your computer and use it in GitHub Desktop.
Save andreasciamanna/d495c8ccdc6a85f94887f9d71fade94b to your computer and use it in GitHub Desktop.
Send an email when an original post with translations is updated
<?php
/*
Plugin Name: WPML Notify on Post Updates
Plugin URI: http://wpml.org
Description: Sends an email when an original post with translations is updated.
Version: 0.0.1
Author: Andrea Sciamanna
Author URI: https://www.onthegosystems.com/team/andrea-sciamanna/
*/
// don't load directly
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
/**
* @param int $post_ID
*/
function wpml_notify_on_post_update( $post_ID ) {
// Skip if it's a REST request (or it will send the same email twice)
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return;
}
$getPostsToUpdate = WPML\FP\pipe(
WPML\Element\API\PostTranslations::getIfOriginal(),
WPML\FP\Fns::reject( WPML\FP\Obj::prop( 'original' ) ),
WPML\FP\Fns::map( WPML\FP\Obj::prop( 'element_id' ) )
);
// The current post is not the original or has no translations
if ( ! $getPostsToUpdate( $post_ID ) ) {
return;
}
// Just a helper function to build anchor tags
$getLink = function ( $url, $text ) {
$link_template = '<a href="%1$s" title="%2$s">%2$s</a>';
return sprintf( $link_template, $url, $text );
};
$post = get_post( $post_ID );
$recipient = get_user_by( 'email', get_option( 'admin_email' ) );
$subject = 'Translations of ' . $post->post_title . ' may need to be updated';
$message = [
'Hello, ' . $recipient->display_name,
'',
'<strong>'. $getLink( get_post_permalink( $post_ID ), $post->post_title ) . '</strong> has been modified and its translations may require an update.',
'',
$getLink( get_bloginfo( 'url' ), get_bloginfo( 'name' ) ),
];
$headers = [ 'Content-Type: text/html; charset=UTF-8' ];
wp_mail( $recipient->user_email, $subject, implode( '<br>', $message ), $headers );
}
add_action( 'post_updated', 'wpml_notify_on_post_update', 10, 2 );
@andreasciamanna
Copy link
Author

andreasciamanna commented Jun 17, 2020

Download the snippet and save it in your wp-content/plugins.

In WordPress, go to Plugins and activate WPML Notify on Post Updates.

This plugin hooks to post_updated which will trigger every time a post is updated.
Then it will check if that post is marked as "original" and if it has any translation.

If all the conditions are met, it will send an email to the user set as admin of the site.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment