Docs

Functions reference

10 min readUpdated November 19, 2026

Every public PHP function in Nahnu Login Shield’s developer API, with its parameters and return values. For a five-minute introduction first, see Developer quick start.

All functions are in the global namespace, begin with nahnls_, and are available once the plugin is active. Wrap every call in function_exists():

if ( function_exists( 'nahnls_check_submission' ) ) {
    // safe to call
}

Functions marked (API 2) need NAHNLS_API_VERSION 2 or later.

At a glance#

FunctionReturnsPurpose
nahnls_widget_html( $args )stringWidget HTML for the active CAPTCHA provider, including the form nonce
nahnls_form_nonce_field()stringHidden form nonce field for forms with their own CAPTCHA markup
nahnls_verify_form_nonce()boolWhether the current POST carries a valid form nonce
nahnls_check_submission( $form_id )true|WP_ErrorVerify a form submission
nahnls_enqueue_widget_assets()voidLoad the widget script and styles on the page
nahnls_markup_allowed_html()arrayAllowed HTML for wp_kses() when you output widget markup
nahnls_get_ip()stringReal visitor IP (proxy-aware)
nahnls_is_locked_out( $ip )boolIs the IP currently locked out?
nahnls_is_ip_blocked( $ip )boolIs the IP on the blocklist?
nahnls_is_widget_active()boolIs a CAPTCHA provider configured?
nahnls_get_country()string|nullVisitor’s country code
nahnls_log_event( $event, $detail, $ip, $username )voidWrite to the event log
nahnls_get_settings()arrayAll settings
nahnls_feature_enabled( $feature )boolStable on/off flags (API 2)
nahnls_passkey_button( $args )stringPasskey sign-in button
nahnls_magic_link_url( $redirect )stringURL of the magic-link request page
nahnls_magic_link_form( $args )stringMagic-link request form
nahnls_send_magic_link( $user, $redirect, $args )true|WP_ErrorSend a magic link by code
nahnls_user_passkeys( $user_id )arrayA user’s passkeys (public fields)
nahnls_user_has_passkey( $user_id )boolDoes the user have a passkey?
nahnls_delete_passkey( $user_id, $credential_id )boolRemove a passkey
nahnls_user_can_use_passkeys( $user )boolAre passkeys allowed for this user?
nahnls_user_can_use_magic_link( $user )boolAre magic links allowed for this user?
nahnls_user_2fa_status( $user_id )arraySummary of a user’s 2FA
nahnls_user_requires_2fa( $user )boolWould this user be challenged? (API 2)
nahnls_start_2fa_challenge( $user, $args )array|WP_ErrorStart 2FA without a redirect (API 2)
nahnls_account_security_panel( $args )stringThe Login & security panel
nahnls_enqueue_auth_script()voidLoad NAHNLSAuth without passkeys (API 2)

Forms and CAPTCHA#

nahnls_check_submission( $form_id )

Checks a form submission against the active rules: the hidden form nonce, the JavaScript marker (if the presence check is on), and the CAPTCHA provider’s verification. Call it in the code that handles your form’s POST.

ParameterTypeDefaultDescription
$form_idstring'custom'A label for the form, passed to your hooks

Returns: true on pass, or a WP_Error on block. The error message is written for visitors.

$result = nahnls_check_submission( 'contact_form' );
if ( is_wp_error( $result ) ) {
    return new WP_Error( 'blocked', $result->get_error_message() );
}

The submission must carry the hidden nahnls_form_nonce field. nahnls_widget_html() adds it. Without a valid nonce the function reads no protection fields, so the check fails. With Require JavaScript on (the default) or reCAPTCHA v3, the message is “Security check expired. Please reload the page and try again.” With other providers you get that provider’s failure message.

Hooks that fire inside this function are listed in Actions and filters.

nahnls_widget_html( $args )

Returns the widget HTML for the active CAPTCHA provider. Place it inside your <form>, before the submit button. It also loads the scripts and styles the widget needs.

ParameterTypeDefaultDescription
$args['form_id']string'custom'Form identifier. In ajax context it is also the reCAPTCHA v3 action
$args['echo']boolfalseEcho instead of returning
$args['context']string'page''page' for server-rendered forms, 'ajax' for forms built by JavaScript

Returns: string. With the provider set to None, only the hidden fields are returned.

echo nahnls_widget_html( [ 'form_id' => 'my_form' ] ); // phpcs:ignore
nahnls_widget_html( [ 'form_id' => 'my_form', 'echo' => true ] );

For ajax context, see CAPTCHA widget in JavaScript forms.

nahnls_form_nonce_field()

Returns the hidden field <input type="hidden" name="nahnls_form_nonce" value="...">. Every form checked by nahnls_check_submission() must contain it. nahnls_widget_html() already includes it, so you only need this function when you print your own CAPTCHA markup.

Returns: string (HTML, not echoed).

nahnls_verify_form_nonce()

Whether the current POST carries a valid form nonce.

Returns: bool

nahnls_is_widget_active()

Whether a CAPTCHA provider is set (anything other than None).

Returns: bool

if ( nahnls_is_widget_active() ) {
    echo nahnls_widget_html();
}

nahnls_enqueue_widget_assets( $localize )

Loads the widget script and styles on the current page. Call it on wp_enqueue_scripts when a form is added later by AJAX, so that NAHNLSWidget is on the page when the form arrives. The optional $localize argument (default true) also passes the widget settings to the script.

Returns: nothing.

add_action( 'wp_enqueue_scripts', function () {
    if ( function_exists( 'nahnls_enqueue_widget_assets' ) ) {
        nahnls_enqueue_widget_assets();
    }
} );

nahnls_markup_allowed_html()

Returns the list of HTML tags and attributes that widget markup needs, in the format wp_kses() expects. Use it when you pass widget markup through wp_kses() before sending it in an AJAX response.

Returns: array

$widget = nahnls_widget_html( [ 'form_id' => 'nav_login', 'context' => 'ajax' ] );
wp_send_json_success( [ 'html' => $form_html . wp_kses( $widget, nahnls_markup_allowed_html() ) ] );

Visitor and status checks#

nahnls_get_ip()

The visitor’s real IP address, using your Trust proxy headers setting. See Lockouts are keyed to the wrong IP (proxies and CDNs).

Returns: string

nahnls_is_locked_out( $ip )

Whether an IP is currently locked out by the brute-force system.

ParameterTypeDefaultDescription
$ipstringthe current visitor’s IPIP address to check

Returns: bool

if ( nahnls_is_locked_out() ) {
    wp_die( 'Too many failed attempts.' );
}

nahnls_is_ip_blocked( $ip )

Whether an IP is on the manual blocklist.

ParameterTypeDefaultDescription
$ipstringthe current visitor’s IPIP address to check

Returns: bool

nahnls_get_country()

The visitor’s country as a two-letter code (ISO 3166-1 alpha-2), from CDN headers or the lookup service you chose on the Geo tab.

Returns: string|null, for example 'US', or null when the country can’t be detected or geo-blocking isn’t set up.

if ( 'US' === nahnls_get_country() ) {
    // US-specific logic
}

Log and settings#

nahnls_log_event( $event, $detail, $ip, $username )

Writes an entry to the event log, so your own events appear on the Log tab with the plugin’s.

ParameterTypeDefaultDescription
$eventstringrequiredEvent name. Maximum 32 characters
$detailstring''Short description. Maximum 120 characters
$ipstringthe current visitor’s IPIP address
$usernamestringthe current user’s loginUsername
nahnls_log_event( 'custom_block', 'Blocked by my plugin', '', 'john' );

Event names are sanitized (lowercase letters, numbers, dashes and underscores). Long values are cut to the column size.

nahnls_get_settings()

All plugin settings, merged with the defaults.

Returns: array

$s = nahnls_get_settings();
$provider = $s['captcha_provider']; // for example 'oopspam'

Prefer nahnls_feature_enabled() for simple on/off questions. Setting names can change between versions.

nahnls_feature_enabled( $feature ) (API 2)

Whether a feature is on. Unknown names return false.

$featureTrue when
two_factorTwo-factor authentication is on and not switched off by NAHNLS_DISABLE_2FA
passkeysPasskey sign-in is on and the request is a secure context (HTTPS or localhost)
magic_linkEmail login links are on
login_protectionLogin protection, the JavaScript check or a CAPTCHA provider is on
wc_login_protectionThe WooCommerce login form is protected
account_panelThe Login & security tab is registered in WooCommerce My Account

Returns: bool

nahnls_feature_enabled( 'account_panel' ) reflects whether the Login & security tab has been registered, so call it from init or later.

Passwordless sign-in#

Passkeys and magic links are switched on separately on the Passwordless tab. When a feature is off, these functions return '', false or a WP_Error, so you can call them without checking first.

nahnls_passkey_button( $args )

Renders a “Sign in with a passkey” button for a custom login form. Loads its scripts for you. Returns '' when passkeys are off or the page isn’t HTTPS.

ParameterTypeDefaultDescription
$args['label']string“Sign in with a passkey”Button text
$args['class']string''Extra CSS class(es) on the button
$args['redirect']stringredirect_to, or the dashboardWhere to go after sign-in (validated with wp_validate_redirect)
$args['echo']boolfalseEcho instead of returning

Returns: string. Shortcode: [nahnls_passkey_button label="Use a passkey" redirect="/account/" class="btn"].

The button reads the form’s “Remember me” checkbox (rememberme).

nahnls_magic_link_url( $redirect )

The address of the built-in “Email me a login link” page on the login screen. '' when magic links are off.

Returns: string

<a href="<?php echo esc_url( nahnls_magic_link_url( home_url( '/account/' ) ) ); ?>">Email me a login link</a>

nahnls_magic_link_form( $args )

A small, self-contained request form. When login protection is on, the JavaScript marker and the CAPTCHA widget are included, so the request passes the same checks as the login page.

ParameterTypeDefaultDescription
$args['redirect']string''Where the emailed link lands
$args['label']string“Email or username”Field label
$args['placeholder']string''Input placeholder
$args['submit']string“Send login link”Button text
$args['class']string''Extra class(es) on the form
$args['input_class'], $args['button_class']stringnahnls-ml-input, nahnls-ml-submitClasses for your CSS
$args['echo']boolfalseEcho instead of returning

Returns: string. Shortcode: [nahnls_magic_link_form redirect="/account/" submit="Send me a link"].

nahnls_send_magic_link( $user, $redirect, $args )

Emails a one-time login link from code, for invitations and support tools. It follows the role limits and the user’s opt-out. It also follows the per-account rate limit, unless you pass force. The token is never returned.

ParameterTypeDefaultDescription
$userint, string or WP_UserrequiredID, login, email or user object
$redirectstringthe dashboardWhere the link lands
$args['force']boolfalseSkip the per-account rate limit
$args['ip']stringthe request IPIP written to the log and the email
$args['origin']string'''wc' makes a later 2FA step open on the WooCommerce My Account page (API 2)

Returns: true or a WP_Error with one of these codes: nahnls_disabled, nahnls_unknown_user, nahnls_not_allowed, nahnls_account_rate_limited, nahnls_no_email.

$sent = nahnls_send_magic_link( $user_id, home_url( '/welcome/' ), [ 'force' => true ] );
if ( is_wp_error( $sent ) ) {
    error_log( $sent->get_error_message() );
}

Passkey helpers

FunctionReturnsPurpose
nahnls_user_passkeys( $user_id )arrayPublic fields only: id, name, aaguid, transports, created, last_used. Never the public key
nahnls_user_has_passkey( $user_id )boolAt least one passkey is registered
nahnls_delete_passkey( $user_id, $credential_id )boolRemoves one passkey. The current user must own it or have edit_users; otherwise (and in cron or WP-CLI with no user) it returns false
nahnls_user_can_use_passkeys( $user )boolFeature on, role allowed and not blocked by a filter. $user is an ID or WP_User
nahnls_user_can_use_magic_link( $user )boolFeature on, role allowed, not opted out and not blocked by a filter

Two-factor authentication#

nahnls_user_requires_2fa( $user ) (API 2)

Whether this user would be asked for a second factor at login. With 2FA on, this is true for everyone in the roles chosen under Apply to roles (an empty list means every role), and for any user who added an authenticator app or passkey. It’s always false while 2FA is off or NAHNLS_DISABLE_2FA is true.

ParameterTypeDescription
$userint or WP_UserUser ID or object

Returns: bool

nahnls_user_2fa_status( $user_id )

A summary of a user’s 2FA.

Returns: array

[
    'enabled'                => true,
    'method'                 => 'totp',      // 'passkey', 'totp', 'email' or ''
    'methods'                => [ 'totp', 'email' ],
    'backup_codes_remaining' => 8,
    'has_passkey'            => false,
]

enabled follows the same rule as nahnls_user_requires_2fa(). methods lists what the user can verify with, strongest first. Email is always included while enabled. A user with [ 'email' ] only has added nothing stronger.

$st = nahnls_user_2fa_status( get_current_user_id() );
if ( $st['enabled'] && [ 'email' ] === $st['methods'] ) {
    echo '<a href="/account/security/">Add an authenticator app or passkey</a>';
}

nahnls_start_2fa_challenge( $user, $args ) (API 2)

Starts a 2FA challenge without a redirect, for logins that run over AJAX (a login drawer or a headless form). Call it only after the password has been checked, for example with wp_authenticate(), which sets no cookie. It never sets or clears a login cookie. The session is created only when the user passes the second factor through the REST routes or the challenge page.

ParameterTypeDefaultDescription
$userint or WP_UserrequiredThe user whose password was just checked
$args['remember']boolfalsePersistent session after the second factor
$args['redirect']stringMy Account (wc) or wp-admin (wp)Where to land afterwards
$args['origin']string'wc' if WooCommerce is active, else 'wp'Which challenge page challenge_url points to

Returns: an array or a WP_Error.

{
  "nonce_key": "3f9c0d1e2a4b5c6d7e8f9a0b1c2d3e4f",
  "methods": ["passkey", "totp", "email"],
  "primary": "passkey",
  "email_sent": false,
  "email_masked": "jo•••@gmail.com",
  "challenge_url": "https://example.com/my-account/?nahnls_2fa=3f9c…",
  "expires_in": 600
}

methods is in priority order (passkey, then authenticator app, then email). The code is emailed automatically only when email is the primary method. Error codes: nahnls_disabled, nahnls_not_required (set the login cookie yourself), nahnls_unknown_user, and nahnls_mail_failed (the error data holds challenge_url and nonce_key so you can fall back).

Finish the challenge with the REST routes 2fa/verify, 2fa/email and 2fa/passkey/*, or the matching NAHNLSAuth methods. See REST API and JavaScript API (NAHNLSAuth).

$check = nahnls_check_submission( 'nav_login' );
if ( is_wp_error( $check ) ) {
    wp_send_json_error( [ 'message' => $check->get_error_message() ], 400 );
}
$user = wp_authenticate( $login, $password ); // No cookie yet.
if ( is_wp_error( $user ) ) {
    wp_send_json_error( [ 'message' => $user->get_error_message() ], 401 );
}
if ( nahnls_user_requires_2fa( $user ) ) {
    $c = nahnls_start_2fa_challenge( $user, [ 'remember' => $remember, 'redirect' => $redirect ] );
    if ( is_wp_error( $c ) ) {
        wp_send_json_error( [ 'message' => $c->get_error_message() ], 500 );
    }
    wp_send_json_success( [ 'two_factor' => $c ] );
}
wp_set_auth_cookie( $user->ID, $remember );
do_action( 'wp_login', $user->user_login, $user );
wp_send_json_success( [ 'redirect' => $redirect ] );
Code
$check = nahnls_check_submission( 'nav_login' );
if ( is_wp_error( $check ) ) {
    wp_send_json_error( [ 'message' => $check->get_error_message() ], 400 );
}
$user = wp_authenticate( $login, $password ); // No cookie yet.
if ( is_wp_error( $user ) ) {
    wp_send_json_error( [ 'message' => $user->get_error_message() ], 401 );
}
if ( nahnls_user_requires_2fa( $user ) ) {
    $c = nahnls_start_2fa_challenge( $user, [ 'remember' => $remember, 'redirect' => $redirect ] );
    if ( is_wp_error( $c ) ) {
        wp_send_json_error( [ 'message' => $c->get_error_message() ], 500 );
    }
    wp_send_json_success( [ 'two_factor' => $c ] );
}
wp_set_auth_cookie( $user->ID, $remember );
do_action( 'wp_login', $user->user_login, $user );
wp_send_json_success( [ 'redirect' => $redirect ] );

Front end#

nahnls_account_security_panel( $args )

The full Login & security panel (passkeys, two-factor, sign-in options) for the signed-in user, with its styles and scripts loaded. Visitors who aren’t signed in see a sign-in prompt.

ParameterTypeDefaultDescription
$args['ui']string'plain''plain' for neutral classes, 'wc' for WooCommerce classes
$args['echo']boolfalseEcho instead of returning

Returns: string. Shortcode: [nahnls_account_security].

nahnls_enqueue_auth_script() (API 2)

Loads nahnls-auth.js with its REST settings and translated messages, even when passkeys are off. Call it on any page that uses NAHNLSAuth.twoFactorVerify(), twoFactorEmail(), twoFactorPasskey() or requestMagicLink().

add_action( 'wp_enqueue_scripts', function () {
    if ( defined( 'NAHNLS_API_VERSION' ) && NAHNLS_API_VERSION >= 2 && function_exists( 'nahnls_enqueue_auth_script' ) ) {
        nahnls_enqueue_auth_script();
        nahnls_enqueue_widget_assets();
    }
} );

Constants#

ConstantMeaning
NAHNLS_API_VERSIONLevel of the public API. Currently 2
NAHNLS_VERSIONPlugin version

Constants that you define in wp-config.php (NAHNLS_BYPASS_IP, NAHNLS_DISABLE_2FA and the edge blocking keys) are described in their own topics.

Was this helpful?

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only