# Custom Action

#### Introduction to Custom Action Functionality in WPLoyalty

The Custom Action feature in WPLoyalty provides an additional method for store owners to award loyalty points to customers for specific actions. This functionality is especially beneficial for campaigns like Achievement Campaigns, where users can earn points by reaching milestones such as Daily Sign-In or Moving Up a Level. The Custom Action mechanism allows for greater flexibility, enabling points and rewards to be triggered by custom events like form submissions or other user-specific actions.

This feature can be extended to a limitless number of custom triggers, provided the necessary conditions are met, such as the inclusion of a user\_email parameter in the action or filter. In this documentation, we will guide you through setting up Custom Actions in WPLoyalty using an example of integrating it with Elementor Forms.

***

#### Overview of Custom Action

The Custom Action functionality in WPLoyalty allows you to customize how and when your customers earn loyalty points beyond predefined actions such as sign-ins or purchases. By implementing custom hooks, store owners can trigger actions such as earning loyalty points when users perform specific tasks on the website, such as submitting a form or interacting with other third-party integrations.

**Requirements**

To successfully set up a custom action:

* The action or filter you want to trigger must include user\_email as a parameter. This ensures that the custom action can be executed for the correct user.
* Store owners should have basic knowledge of WordPress actions and filters to trigger the custom logic.

{% hint style="info" %}
Please note that before proceeding, you must have installed and activated the WPLoyalty PRO plugin. It is important to note that the below-discussed Custom Action requires the PRO version. &#x20;

[Get WPLoyalty PRO](https://wployalty.net/pricing/)
{% endhint %}

***

#### Implementation Example: Integrating Custom Action with Elementor Forms

In this section, we will walk through an example where customers can earn points when submitting an Elementor Form. This will use the elementor\_pro/forms/new\_record hook to trigger the custom action. Kindly check with the [Elementor Developer Documentation](https://developers.elementor.com/docs/hooks/forms/#form-new-record)

**Scenario: Earn Points on Form Submission**

Goal: Allow a customer to earn loyalty points when they submit a form, ensuring that they only earn once.

**Step 1: Design the Form**

1. Create the form in Elementor where customers can input their details (e.g., name, email, etc.).
2. Get the form name and the ID of the email field from the form settings.

For reference, watch the video tutorial: \[[Video link](https://www.dropbox.com/scl/fi/kdnhqer2hd7hf62infhaa/Creating-form-using-elementor.webm?rlkey=lx9ukvxrcz9s122x4ky3lx69q\&e=1\&st=vs73sbc2\&dl=0)].

**Step 2: Create the Hook to Trigger the Custom Action**

Create a hook that will trigger the custom action when a user submits the form.

```
add_action('elementor_pro/forms/new_record', function($record, $handler) {
  $form_name = $record->get_form_settings('form_name');
  if ('My form' !== $form_name) {
      return;
  }
  $form_data = $record->get('fields');
  $email_field_id = 'email';
  $submitted_email = isset($form_data[$email_field_id]['value']) ? $form_data[$email_field_id]['value'] : '';

  do_action('custom_newsletter_submitted', $submitted_email);
}, 10, 2);
```

**Explanation:**

* We first check if the submitted form is the one we created by verifying the form name.
* Next, we retrieve the email field from the form using the field ID.
* Once we obtain the email, we trigger a custom action (custom\_newsletter\_submitted) with the email as a parameter.

**Step 3: Trigger the Custom Action**

Now, trigger the Custom Action with the email parameter:

```
add_action('custom_newsletter_submitted', function($email) {
   if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
       return;
   }
   $action_data = [
       'user_email'           => $email,
       'achievement_type'     => 'custom_action',
       'action_sub_type'      => 'extra_action',
       'action_sub_value'     => 0,
       'allowed_campaign_ids' => [34]
   ];
   if (class_exists('\Wlr\App\Premium\Helpers\Achievement')) {
       $achievement_helper = \Wlr\App\Premium\Helpers\Achievement::getInstance();
       $achievement_helper->applyEarnCustomAction($action_data);
   }
}, 10, 1);


```

**Explanation:**

* We construct the action data using the email in the user\_email field.
* The achievement\_type is set to custom\_action.
* We define which campaigns the user can earn from by setting the allowed\_campaign\_ids parameter.
* The applyEarnCustomAction method is called to apply the points.

**Step 4: Validate Before Processing the Earnings**

We will now validate the custom action before it is processed using the wlr\_achievement\_check\_status hook.

```
add_filter('wlr_achievement_check_status', function($status, $data) {
   if (!isset($data['campaign_id']) || empty($data['campaign_id'])) {
      return false;
   }
   if (!in_array($data['campaign_id'], $data['allowed_campaign_ids'])) {
      return false;
   }
   //Check for one time only
   $earn_campaign_where = [
      'user_email'       => ['operator' => '=', 'value' => $data['user_email']],
      'action_type'      => ['operator' => '=', 'value' => 'achievement'],
      'transaction_type' => ['operator' => '=', 'value' => 'credit'],
      'campaign_id'      => ['operator' => '=', 'value' => $data['campaign_id']],
      'action_sub_type'  => ['operator' => '=', 'value' => 'extra_action']
   ];
   if (!class_exists('\Wlr\App\Models\EarnCampaignTransactions')) {
      return false;
   }
   $earn_campaign_transaction = new \Wlr\App\Models\EarnCampaignTransactions();
   $transaction_data = $earn_campaign_transaction->getQueryData($earn_campaign_where, '*', [], false);
   if (!empty($transaction_data)) {
      return false;
   }

   return true;
}, 10, 2);


```

**Explanation:**

* First, we validate that the campaign\_id matches the allowed campaigns.
* Next, we query the EarnCampaignTransactions model to check if the user has already earned from this campaign.
* If a transaction exists, we prevent the earning, otherwise, we allow the earning.

***

#### Advanced Tips

**Bonus Tip: Customizing the Earning Logic**

You can further customize the earning logic by interacting with the EarnCampaignTransactions object:

* You can loop through past transactions to limit the number of times a user can earn for a particular action.
* Modify the logic to meet specific business needs, like awarding points based on the number of actions performed.

The Custom Action functionality in WPLoyalty is highly customizable to fit any business requirements, and you can tailor the logic to suit your needs, whether you're allowing one-time earnings or setting limits based on user behavior.

***

By following this guide, you can integrate custom actions into your WPLoyalty campaigns, offering customers more ways to earn points and rewards based on their interactions with your site.

{% hint style="info" %}
The above-discussed Custom Action scenarios require a PRO version.

[Get WPLoyalty PRO ](https://wployalty.net/pricing/)
{% endhint %}

**Next Steps:**

**You may also want to check out these helpful guides:**

* [To learn about setting up Tiered Levels or VIP Customer Rewards, click here. ](https://docs.wployalty.net/customers-levels-and-vip/creating-tiered-levels-vip-customer-rewards)
* [For more information on additional conditions available in WPLoyalty, click here. ](https://docs.wployalty.net/campaigns/campaign-rules)
* [If you want to learn about offering points for every dollar customers spend, create a Point for Purchase Campaign. ](https://docs.wployalty.net/campaign-types/points-for-purchase)
* [To discover how to convert earned points to discounts or dollars, create a Point Conversion Reward. ](https://docs.wployalty.net/reward-types/points-conversion)
* [To learn about the various campaign types available, click here.](https://docs.wployalty.net/campaigns/campaign-types)

**Still Unclear ?**

If you need any assistance, please create a [support request ](https://wployalty.net/support/)at our ticket system. We are always happy to assist you :)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.wployalty.net/campaign-types/achievement-campaign/custom-action.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
