25% off ProSNIPC25OFF

WPForms: Restrict Form to Logged-In Users Only

Intercepts the WPForms shortcode and replaces the form with a login prompt for visitors who are not authenticated, using the WordPress pre_do_shortcode_tag filter.

PHPby SnipCraft
php
<?php
if ( function_exists( 'wpforms' ) && ! function_exists( 'scseed_wpf_require_login' ) ) {
    /**
     * Replaces [wpforms] shortcode output with a login message for guests.
     * Only affects [wpforms] shortcodes — all others are untouched.
     *
     * To restrict a specific form only, uncomment the $attr['id'] check below.
     *
     * @param string|false $output Return false to let WordPress process normally.
     * @param string       $tag    The shortcode tag name.
     * @param array        $attr   Shortcode attributes.
     * @param array        $m      Regex match array from the shortcode parser.
     * @return string|false
     */
    function scseed_wpf_require_login( $output, $tag, $attr, $m ) {
        if ( $tag !== 'wpforms' ) {
            return $output; // Let all other shortcodes through.
        }

        // Optionally restrict only a specific form:
        // if ( (int) ( $attr['id'] ?? 0 ) !== 42 ) { return $output; }

        if ( is_user_logged_in() ) {
            return false; // false = "not handled here", WordPress runs the shortcode normally.
        }

        $login_url = wp_login_url( get_permalink() );
        return '<p class="scseed-login-required">'
            . 'You must be <a href="' . esc_url( $login_url ) . '">logged in</a> to access this form.'
            . '</p>';
    }
    add_filter( 'pre_do_shortcode_tag', 'scseed_wpf_require_login', 10, 4 );
}
#access-control#forms#login#members-only#wpforms