avatar Deluxe Blog Tips About Projects

Displaying A Login Form In Sidebar Now Made Easy In WordPress 3.0

Displaying A Login Form In Sidebar Now Made Easy In WordPress 3.0

In WordPress 2.x and ealier, to display a login form in sidebar, we must use some raw PHP codes. But since version 3.0, WordPress provides new function, wp_login_form(), to make it done easily. In this article, we'll see how the function wp_login_form() works and how to implement it in WordPress sidebar.

The function wp_login_form() takes many parameters:

wp_login_form(array(
    'echo' => true,
    'redirect' => site_url($_SERVER['REQUEST_URI']),
    'form_id' => 'loginform',
    'label_username' => __('Username'),
    'label_password' => __('Password'),
    'label_remember' => __('Remember Me'),
    'label_log_in' => __('Log In'),
    'id_username' => 'user_login',
    'id_password' => 'user_pass',
    'id_remember' => 'rememberme',
    'id_submit' => 'wp-submit',
    'remember' => true,
    'value_username' => ,
    'value_remember' => false
));

The most important are:

  • echo: display (true) or not (false) login form. If not, it returns HTML string that you can put anywhere. Default is true.
  • redirect: the URL of web page to redirect user to after login. The default value is site_url( $_SERVER['REQUEST_URI'] ), that means current URL.
  • form_id: ID of login form. Default is loginform. You might want to know this for styling the login form.
  • remember: (true/false) Whether to remember the values. Default is true.

To see all parameters and their meanings, you can go to the Codex.

Now, let's see an example of wp_login_form's usage. We'll check if user is logged in or not. If user logged in, we'll display a greeting and a logout link. If not, we'll display a login form. So, open your sidebar.php file and paste the following code into it:

global $user_login;
if (is_user_logged_in()) {
    echo 'Hello, ', $user_login, '. <a href="', wp_logout_url(), '" title="Logout">Logout</a>';
} else {
    wp_login_form();
}

That's really simple and clean, isn't it?

Adding a login form in sidebar is a good way to improve user experience in your WordPress blog, especially when you want your users do everything in the front-end only.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Comments