A lot of people want the ability to display the WordPress login form within the content of one of their site’s pages. By default, WordPress does not provide any way to do this, so today I am going to show you a simple shortcode to display the login form.
The plugin only requires one simple function that will return the contents (the login form) of the wp_login_form() function.
function login_form_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(
'redirect' => ''
), $atts ) );
if (!is_user_logged_in()) {
if($redirect) {
$redirect_url = $redirect;
} else {
$redirect_url = get_permalink();
}
$form = wp_login_form(array('echo' => false, 'redirect' => $redirect_url ));
}
return $form;
}
add_shortcode('loginform', 'login_form_shortcode');
Inside of the above function we’ve added a call to the extract function in order to retrieve the attributes passed to the shortcode which allows us to specify the redirect url, or the location the user should be sent upon successful login.
After we get the shortcode attributes, we do a quick check to see if the current user is logged in, as there is no reason to display the form if they are already logged in. If the user is not logged in, then we return the wp_login_form() function, which will display the actual login form.
Finally, after the closing } we use the add_shortcode() function to make the shortcode available for use in the content editor.
Now we can display our form on any page or post like this:
[loginform redirect="http://my-redirected-url.com"]
Or if you want to include it in your page template you can do so like this:
<?php echo do_shortcode( '[loginform redirect="http://my-redirected-url.com"]' ); ?>