Skip to content

Instantly share code, notes, and snippets.

@mikelittle
Last active January 13, 2023 16:57
Show Gist options
  • Save mikelittle/f73ce199705d85f9a91431e9b88ad60a to your computer and use it in GitHub Desktop.
Save mikelittle/f73ce199705d85f9a91431e9b88ad60a to your computer and use it in GitHub Desktop.
<?php
/**
* Example code to add Workflow notifications to Altis Native Analytics
*
*/
Use Altis\Analytics\Experiments;
use HM\Workflows;
use HM\Workflows\Event;
use HM\Workflows\Workflow;
add_action( 'plugins_loaded', static function () {
/**
* Hook into the workflow module for experiment notifications.
*/
// Double check the Workflows plugin is loaded.
if ( ! class_exists( 'HM\Workflows\Event' ) ) {
return;
}
// Remove default notifications.
remove_action( 'altis.experiments.test.ended', 'Altis\Analytics\Experiments\send_post_ab_test_notification', 10 );
// Experiment events.
$events = [
'altis.experiments.test.ended' => __( 'An experiment has ended', 'your-translation-handle' ),
];
foreach ( $events as $event => $label ) {
// Create the event handler.
$event = Event::register( $event );
$event->set_listener( [
'action' => $event->get_id(),
'accepted_args' => 2,
] );
$event->add_recipient_handler( 'post_author', function ( string $test_id, int $post_id ) {
$post = get_post( $post_id );
return $post->post_author;
}, __( 'Post author', 'your-translation-handle' ) );
$event->add_recipient_handler( 'post_assignees', function ( string $test_id, int $post_id ) {
return Workflows\get_post_assignees( $post_id );
}, __( 'Post assignees', 'your-translation-handle' ) );
$event->add_message_tags( [
'test.title' => function ( string $test_id ) {
$test = Experiments\get_post_ab_test( $test_id );
return $test['label'];
},
'post.title' => function ( string $test_id, int $post_id ) {
$post = get_post( $post_id );
$variants = Experiments\get_ab_test_variants_for_post( $test_id, $post_id );
return count( $variants ) ? $variants[0] : $post->post_title;
},
] );
$event->add_message_action(
'view',
__( 'View results', 'your-translation-handle' ),
function ( string $test_id, int $post_id ) {
return get_edit_post_link( $post_id, 'db' ) . '#experiments-' . $test_id;
},
function ( string $test_id, int $post_id ) : array {
return [
'test_id' => $test_id,
'post_id' => $post_id,
];
},
[
'test_id' => 'sanitize_text_field',
'post_id' => 'intval',
]
);
Workflow::register( $event->get_id() )
->when( $event )
->who( [
'post_author',
'post_assignees',
'editor',
'administrator',
] )
->what(
__( 'Your test %test.title% on "%post.title%" has ended', 'your-translation-handle' )
)
->where( 'email' )
->where( 'dashboard' );
}
}, 12 ); // Run a little later.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment