Categories: How To // Wordpress

Redirect To A Different Page In WordPress

The action hook that we are going to use for redirection is commonly misused for including custom page templates. The name of the hook may be misleading for some and there you go.

The hook that we are going to use is the perfect hook to use for page redirections.

For example, let’s say you have a custom query string and you want to redirect user to another page if that query string exists or if the user is not logged in and so on. Not a problem, call action hook, check what you want to check and redirect if required.

So, let’s create a simple page redirect that will redirect all anonymous users to login page.

To create a page redirection, you need to use an action hook that is called before anything is outputted. To do that, we need to call action hook called template_redirect.

/**
 * Redirect all anonymous users to login page.
 *
 * @param	void
 * @return	void
 * @since	1.0
 *
 */
function lessthanweb_template_redirect() {
	//	If user is not logged in.
	if ( ! is_user_logged_in() ) {
		//	Redirect to login page.
		wp_redirect( wp_login_url() );
	}
}
add_action( 'template_redirect', 'lessthanweb_template_redirect' );

Easy as making a pie.

Leave a Reply

Your email address will not be published. Required fields are marked *