Adding custom events
To create a new event, you have to do two things:
- Create a new class that extends
\WPDesk\ShopMagic\Workflow\Event\Event
abstract class. - Inform the ShopMagic that a new event is available.
Creating a new event class
As interface \WPDesk\ShopMagic\Workflow\Event\Event
requires some more in-depth knowledge about Event\<->Automation\<->Filter
interactions, we've created some intermediary abstracts to help you with the most common uses.
- For events that are linked to order data, we've prepared
\WPDesk\ShopMagic\Workflow\Event\OrderCommonEvent
. - For events that are linked to a user, we've prepared
\WPDesk\ShopMagic\Workflow\Event\UserCommonEvent
. - For events that are linked to some new kind of data, you can extend
\WPDesk\ShopMagic\Workflow\Event\Event
.
Creating a new event that is linked to the order
To facilitate the creation of an order-linked event, it's best to extend \WPDesk\ShopMagic\Workflow\Event\OrderCommonEvent
class and override two primary methods: get_name
and initialize
.
The get_name
method defines the name for the event that would be visible in Automations in the admin panel. The initialize
should hook to the WordPress action system and execute run_action
method after the event fires. The order that event hook should receive from WooCommerce should be assigned to the order
property.
Example
An event that is fired when a WooCommerce item is added to the order in admin panel can have an initialize
method defined as:
public function initialize(): void {
add_action( 'woocommerce_ajax_order_items_added', function( $items, $order ) {
$this->order = $order;
$this->run_actions();
}, 10, 2);
}
Informing the ShopMagic plugin about a new event
To integrate a newly created event class, you should use a filter shopmagic/core/events
and add a new class to the event hashmap.
Example
Let's create a new event with the name Invoice Resend
that is fired after the invoice was sent.
namespace YourNamespace;
class InvoiceAfterResendEvent extends \WPDesk\ShopMagic\Workflow\Event\OrderCommonEvent {
public function get_name() {
return __( 'Invoice Resend', 'my-text-domain' );
}
public function initialize() {
add_action( 'woocommerce_after_resend_order_email', function( $order ) {
$this->order = $order;
$this->trigger_automation();
});
}
}
Then we need to inform the ShopMagic event factory using the shopmagic/core/events
filter.
/**
* @param \WPDesk\ShopMagic\Workflow\Event\Event[] $hashmap Hashmap with built in events.
*
* @return \WPDesk\ShopMagic\Workflow\Event\Event[] Hashmap with appended event.
*/
function integrate_custom_shopmagic_event( array $hashmap ) {
require_once(__DIR__ . '/path/to/event/class/if/no/autoloading/used.php');
$hashmap['invoice_resend_evest'] = new \YourNamespace\InvoiceAfterResendEvent();
return $hashmap;
}
add_filter('shopmagic/core/events', 'integrate_custom_shopmagic_event');