Users & Login PHP Beginner

Add a Login Form Shortcode

Put a WordPress login form on any page with [nahnu_login_form], and show a welcome message to users who are already logged in.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 17 lines
add_shortcode( 'nahnu_login_form', function ( $atts ): string {
	$atts = shortcode_atts( [ 'redirect' => '' ], $atts, 'nahnu_login_form' );

	if ( is_user_logged_in() ) {
		return sprintf(
			'<p>You\'re logged in as %s. <a href="%s">Log out</a></p>',
			esc_html( wp_get_current_user()->display_name ),
			esc_url( wp_logout_url( get_permalink() ) )
		);
	}

	return wp_login_form( [
		'echo'     => false,
		'redirect' => $atts['redirect'] ? esc_url_raw( $atts['redirect'] ) : get_permalink(),
		'remember' => true,
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Sending users to wp-login.php takes them away from your site’s design. A login form on a normal page, such as /members/, feels part of the site. This shortcode adds one anywhere.

How it works

wp_login_form() builds WordPress’s own login form, which posts to wp-login.php, so all normal login security, plugins and two-factor checks still apply. With 'echo' => false it returns the HTML for the shortcode.

Logged-in users see their name and a log out link instead. Add redirect="/dashboard/" to send people somewhere specific after logging in.

Things to watch

  • Failed logins still land on wp-login.php to show the error. For a fully custom flow, combine with “Redirect the Login Page to a Custom URL”.
  • Exclude the page from caching, or logged-in users may see the form.

How to test it

Add [nahnu_login_form] to a page and view it logged out. The form should appear. Log in through it and you should return to the same page.

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