Fluentcrm funnel trigger

From Lonsdale201/wp-agent-skills · View interactive version

Fluentcrm funnel trigger is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Build a custom FluentCRM funnel trigger by extending BaseTrigger. Covers the four abstract methods (getTrigger, getFunnelSettingsDefaults, getSettingsFields, handle), the auto-injected __force_run_actions field, the canonical isProcessable / run_multiple / ifAlreadyInFunnel guard, the fluentcrm_funn

How to use this skill

Skill file

FluentCRM: register a custom funnel trigger

For developers building a companion plugin that needs to start a FluentCRM automation when something happens (course enrolled, SaaS webhook arrived, custom CPT published, third-party event). Extends FluentCrm\App\Services\Funnel\BaseTrigger and registers via the fluentcrm_funnel_triggers filter chain. This skill maps the contract verified end-to-end against FluentCRM 3.1.8 source, with the lifecycle order written out in full because timing is where this contract silently breaks.

API stability note

The BaseTrigger abstract class, the fluentcrm_funnel_triggers / fluentcrm_funnel_start_* / fluentcrm_funnel_editor_details_* / fluentcrm_funnel_arg_num_* hook family, and the FunnelProcessor::startFunnelSequence() entry point have been stable across the 2.7+ line. In FluentCRM 3.1.8, active trigger listeners are registered by FunnelHandler::registerEarlyActiveTriggers() on init:2 when the arg-count filter is already present, with a fallback registerActiveTriggers() pass on init:20.

Misconception this skill corrects

"I'll register my trigger on fluent_crm/after_init like the other addons do — it's a clean post-boot hook."

Wrong hook. fluent_crm/after_init runs on init priority 1000 (boot/app.php). In 3.1.8, FluentCRM's FunnelHandler registers core funnel items on init:1, then performs an early active-trigger listener pass on init:2 and a fallback pass on init:20. The early pass only registers trigger listeners whose fluentcrm_funnel_arg_num_{name} filter already exists. By the time fluent_crm/after_init fires, both listener passes have already run.

The visible bug: a trigger like lw_lms_after_grant (which fires with 5 args) either misses events fired during init:10, or gets only $user_id delivered if the fallback listener captured the default arg count. $courseId = (int) ($originalArgs[1] ?? 0) becomes 0. Any guard if ($courseId <= 0) return; silently drops every event.

The fix is one line: instantiate your BaseTrigger subclass on fluentcrm_loaded priority 5 instead of fluent_crm/after_init. FluentCampaign Pro registers its funnel items on init:1, which lands before the init:2 early active-trigger pass.

Other AI-prone misconceptions:

When to use this skill

Trigger when ANY of the following is true:

Lifecycle in one diagram

plugins_loaded:10            ← your plugin instantiates its bootstrap
        ↓
fluentcrm_loaded             ← do_action('fluentcrm_loaded') from boot/app.php:41
                               REGISTER TRIGGERS HERE (priority < 10)
        ↓
fluentcrm_addons_loaded      ← do_action('fluentcrm_addons_loaded') from boot/app.php:42
                               addon boot point
        ↓
init:1                        ← FunnelHandler::registerFunnelItems()
                                 Core trigger/action/benchmark classes register.
                                 Pro IntegrationHandler also registers here.
        ↓
init:2                        ← FunnelHandler::registerEarlyActiveTriggers()
                                 → reads fluentcrm_funnel_settings option
                                 → registers only trigger names whose
                                   fluentcrm_funnel_arg_num_{name} filter exists
        ↓
init:10                       ← FunnelHandler::handle()
                                 → registers automation runner callback
        ↓
init:20                       ← FunnelHandler::registerActiveTriggers()
                                 fallback listener pass for late arg filters
        ↓
init:1000                    ← do_action('fluent_crm/after_init') from boot/app.php:44-46
                               TOO LATE for trigger registration
        ↓
... runtime events fire ...

The single rule: fluentcrm_funnel_arg_num_{name} filter must be in place before the init:2 early active-trigger pass if the underlying event can fire during init. The simplest way to guarantee that is to instantiate your BaseTrigger subclass on fluentcrm_loaded priority 5.

Step 1 — Register on the right hook

<?php
namespace MyPlugin\Modules\Triggers;

use HelloWP\MyPlugin\Support\Dependency;
use HelloWP\MyPlugin\Settings\SettingsRepository;

final class TriggerManager
{
    public function __construct()
    {
        // CRITICAL — this runs before FunnelHandler's init:2 early listener
        // pass. If our BaseTrigger subclass is not instantiated by then,
        // the fluentcrm_funnel_arg_num_{name} filter is missing and init-time
        // events can be missed or reduced to the default one accepted arg.
        add_action('fluentcrm_loaded', [$this, 'registerTriggers'], 5);
    }

    public function registerTriggers(): void
    {
        if (Dependency::isMyServiceActive() && SettingsRepository::isEnabled('triggers', 'my_event')) {
            new MyEventTrigger();
        }
    }
}

new MyEventTrigger() invokes the parent constructor, which calls register() (BaseTrigger.php:14-33) — that's where the four filter / action / arg-num registrations happen.

Step 2 — Extend BaseTrigger

<?php
namespace MyPlugin\Modules\Triggers;

use FluentCrm\App\Services\Funnel\BaseTrigger;
use FluentCrm\App\Services\Funnel\FunnelHelper;
use FluentCrm\App\Services\Funnel\FunnelProcessor;
use FluentCrm\Framework\Support\Arr;

final class MyEventTrigger extends BaseTrigger
{
    public function __construct()
    {
        // Real WP action — fired from somewhere else (your plugin, a third
        // party, WP core). FluentCRM will add_action() to this name.
        $this->triggerName  = 'my_plugin_thing_happened';

        // priority for the fluentcrm_funnel_triggers filter (controls picker order)
        $this->priority     = 12;

        // Argument count this hook fires with. Verified against the do_action
        // call site — see Step 4 if you control the dispatch.
        $this->actionArgNum = 3;

        parent::__construct();
    }

    public function getTrigger()
    {
        return [
            'category'    => __('My Service', 'my-plugin'),
            'label'       => __('Thing Happened', 'my-plugin'),
            'description' => __('Fires when "the thing" happens in My Service.', 'my-plugin'),
            'icon'        => 'fc-icon-trigger',
        ];
    }

    public function getFunnelSettingsDefaults()
    {
        return [
            'subscription_status' => 'subscribed',
        ];
    }

    public function getSettingsFields($funnel)
    {
        return [
            'title'     => __('Thing Happened (My Service)', 'my-plugin'),
            'sub_title' => __('Starts when My Service emits the event.',  'my-plugin'),
            'fields'    => [
                'subscription_status' => [
                    'type'        => 'option_selectors',
                    'option_key'  => 'editable_statuses',
                    'is_multiple' => false,
                    'label'       => __('Subscription Status', 'my-plugin'),
                    'placeholder' => __('Select Status', 'my-plugin'),
                ],
                'subscription_status_info' => [
                    'type'       => 'html',
                    'info'       => '<b>' . __('Pending status sends double-optin email.', 'my-plugin') . '</b>',
                    'dependency' => [
                        'depends_on' => 'subscription_status',
                        'operator'   => '=',
                        'value'      => 'pending',
                    ],
                ],
            ],
        ];
    }

    public function getFunnelConditionDefaults($funnel)
    {
        return [
            'update_type'  => 'update', // skip_all_actions | skip_update_if_exist | update
            'thing_ids'    => [],
            'run_multiple' => 'no',
        ];
    }

    public function getConditionFields($funnel)
    {
        return [
            'update_type' => [
                'type'    => 'radio',
                'label'   => __('If Contact Already Exists?', 'my-plugin'),
                'help'    => __('What happens when the contact is already in the database.', 'my-plugin'),
                'options' => FunnelHelper::getUpdateOptions(),
            ],
            'thing_ids' => [
                'type'        => 'rest_selector',
                'option_key'  => 'my_plugin_things',  // see fluentcrm-rest-options skill
                'is_multiple' => true,
                'label'       => __('Target Things', 'my-plugin'),
                'inline_help' => __('Leave blank to run on every event.', 'my-plugin'),
            ],
            'run_multiple' => [
                'type'        => 'yes_no_check',
                'label'       => '',
                'check_label' => __('Restart automation multiple times for the same contact.', 'my-plugin'),
                'inline_help' => __('Without this, contacts already in the funnel are skipped.', 'my-plugin'),
            ],
        ];
    }

    public function handle($funnel, $originalArgs)
    {
        $userId  = (int) ($originalArgs[0] ?? 0);
        $thingId = (int) ($originalArgs[1] ?? 0);

        if ($userId <= 0 || $thingId <= 0) {
            return;
        }

        $subscriberData = FunnelHelper::prepareUserData($userId);
        $subscriberData['source'] = __('My Service', 'my-plugin');

        if (empty($subscriberData['email']) || !is_email($subscriberData['email'])) {
            return;
        }

        $willProcess = $this->isProcessable($funnel, $thingId, $subscriberData);

        // Required parity with FluentCampaign Pro triggers — third-party
        // plugins use this filter to add their own gating without forking.
        $willProcess = apply_filters(
            'fluentcrm_funnel_will_process_' . $this->triggerName,
            $willProcess, $funnel, $subscriberData, $originalArgs
        );

        if (!$willProcess) {
            return;
        }

        // Merge funnel-level settings (subscription_status etc.) into subscriberData
        // and translate to the wire format FunnelProcessor expects.
        $subscriberData = wp_parse_args($subscriberData, $funnel->settings);
        $subscriberData['status'] = !empty($subscriberData['subscription_status'])
            ? $subscriberData['subscription_status']
            : 'subscribed';
        unset($subscriberData['subscription_status']);

        (new FunnelProcessor())->startFunnelSequence($funnel, $subscriberData, [
            'source_trigger_name' => $this->triggerName,
            'source_ref_id'       => $thingId,
        ]);
    }

    private function isProcessable($funnel, int $thingId, array $subscriberData): bool
    {
        $conditions = (array) $funnel->conditions;

        if (Arr::get($conditions, 'update_type') === 'skip_all_if_exist'
            && FunnelHelper::getSubscriber($subscriberData['email'])
        ) {
            return false;
        }

        $thingIds = Arr::get($conditions, 'thing_ids', []);
        if (!empty($thingIds) && !in_array($thingId, array_map('intval', (array) $thingIds), true)) {
            return false;
        }

        $subscriber = FunnelHelper::getSubscriber($subscriberData['email']);
        if ($subscriber && FunnelHelper::ifAlreadyInFunnel($funnel->id, $subscriber->id)) {
            $multipleRun = Arr::get($conditions, 'run_multiple') === 'yes';
            if ($multipleRun) {
                FunnelHelper::removeSubscribersFromFunnel($funnel->id, [$subscriber->id]);
            } else {
                return false;
            }
        }

        return true;
    }
}

Step 3 — When to use a real WP action vs a custom one

Two valid shapes:

Real WP action (preferred when one exists). Set $triggerName to the action name a third-party plugin / WP core / your own plugin already fires. FluentCRM picks it up automatically:

$this->triggerName  = 'tutor_after_enrolled';   // real Tutor LMS hook
$this->actionArgNum = 2;                        // matches do_action('tutor_after_enrolled', $courseId, $userId)

No bridging needed.

Custom action with a bridge (for synthesised / filtered events). When the underlying event needs filtering before the trigger runs (e.g. "only fire on order created, not on every status change"), pick a unique custom name and fire it yourself:

// In a separate "dispatcher" class loaded on fluentcrm_loaded too:
add_action('woocommerce_new_order', function ($orderId, $order) {
    // Skip if no published funnel uses this trigger — saves DB lookups.
    $hasActiveFunnel = \FluentCrm\App\Models\Funnel::where('status', 'published')
        ->where('trigger_name', 'my_custom_woo_status_changed')
        ->exists();
    if (!$hasActiveFunnel) {
        return;
    }

    do_action('my_custom_woo_status_changed', $orderId, $order);
}, 22, 2);

The trigger class then listens on my_custom_woo_status_changed with actionArgNum = 2. Same lifecycle rules apply — register on fluentcrm_loaded priority 5.

Step 4 — How FluentCRM connects the dots

Follow the chain:

  1. Your getTrigger() return value is filtered into fluentcrm_funnel_triggers (BaseTrigger.php:21) — that's how the picker UI sees your trigger.
  2. When the admin saves a funnel using your trigger name, FunnelController calls FunnelHandler::resetFunnelIndexes() which writes your trigger name into the fluentcrm_funnel_settings option (FunnelHandler.php:144-170).
  3. On the next request, FunnelHandler::registerEarlyActiveTriggers() reads that option on init:2 and adds the listener when has_filter('fluentcrm_funnel_arg_num_'.$triggerName) is true. FunnelHandler::registerActiveTriggers() repeats the pass on init:20 as a fallback. In both passes $argNum = apply_filters('fluentcrm_funnel_arg_num_'.$triggerName, 1).
  4. When do_action($triggerName, ...args) fires, the listener calls mapTriggers() which dispatches do_action("fluentcrm_funnel_start_{$triggerName}", $funnel, $originalArgs) (FunnelHandler.php:120).
  5. That action is what BaseTrigger::register() listens on at fluentcrm_funnel_start_{$triggerName} (BaseTrigger.php:25) → invokes your handle($funnel, $originalArgs).

Two important consequences:

Critical rules

Common mistakes

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.