Skip to content

Instantly share code, notes, and snippets.

@brandonjp
Last active August 3, 2023 19:58
Show Gist options
  • Save brandonjp/44d1370107699bbc891b959aa3eb727b to your computer and use it in GitHub Desktop.
Save brandonjp/44d1370107699bbc891b959aa3eb727b to your computer and use it in GitHub Desktop.
CustomUserRedirect - Redirect Users After Login [SnipSnip.pro] - Redirect users upon login based on user roles. Use custom roles and redirect rules. More info at: https://snipsnip.pro/s/730
{
"generator": "Code Snippets v3.4.2.2",
"date_created": "2023-08-03 19:38",
"snippets": [
{
"id": 63,
"name": "CustomUserRedirect - Redirect Users After Login [SnipSnip.pro]",
"desc": "<p>CustomUserRedirect - Redirect Users After Login [SnipSnip.pro] - Redirect users upon login based on user roles. Easily add/remove/edit the custom roles and redirection rules. Include dynamic data, such as <code>{{username}}</code>, <code>{{user_id}}</code>, and more, including user meta with <code>{{user_meta:META_KEY_HERE}}</code>. *Notes: This class assumes that each user has only one role. If a user has multiple roles, they will be redirected based on the first role found in their role list. Also, be aware of privacy considerations when using tokens like <code>{{user_email}}</code> and <code>{{user_ip}}</code>, as these could potentially expose sensitive user information. <a id=\"sample-permalink\" href=\"https://snipsnip.pro/s/730\">https://snipsnip.pro/s/730</a></p>",
"code": "// CustomUserRedirect - Redirect Users After Login [SnipSnip.pro] - https://snipsnip.pro/s/730\nif (!class_exists('CustomUserRedirect')) {\n class CustomUserRedirect {\n // Define custom roles and rules as an associative array\n private $rules = [\n 'subscriber' => '/series/{{username}}',\n // 'contributor' => '',\n // 'author' => '',\n // 'editor' => '',\n 'administrator' => '/wp-admin/edit.php?post_type=podcast',\n 'default' => '/', // Default redirect for any other role\n ];\n\n public function __construct() {\n // Hook the redirect function to the 'wp_login' action\n add_action('wp_login', [$this, 'redirectUser'], 10, 2);\n }\n\n public function redirectUser($user_login, $user) {\n // Get the user roles\n $roles = $user->roles;\n\n // Check each role and redirect accordingly\n foreach ($roles as $role) {\n if (array_key_exists($role, $this->rules)) {\n // Replace the tokens with the actual values\n $redirect_url = $this->replaceTokens($this->rules[$role], $user);\n wp_redirect(home_url($redirect_url));\n exit;\n }\n }\n\n // If no matching role found, redirect to the default location\n wp_redirect(home_url($this->rules['default']));\n exit;\n }\n\n private function replaceTokens($url, $user) {\n // Define custom tokens and their replacement values\n $tokens = [\n '{{username}}' => $user->user_login,\n '{{user_id}}' => $user->ID,\n '{{current_page}}' => $_SERVER['REQUEST_URI'],\n '{{website_url}}' => get_site_url(),\n '{{user_slug}}' => $user->user_nicename,\n '{{referrer}}' => wp_get_referer(),\n '{{user_ip}}' => $_SERVER['REMOTE_ADDR'],\n '{{user_ip_hash}}' => hash('sha256', $_SERVER['REMOTE_ADDR']),\n '{{user_email}}' => $user->user_email,\n '{{user_email_hash}}' => hash('sha256', $user->user_email),\n '{{user_registered}}' => $user->user_registered,\n '{{current_date}}' => date('Ymd'), // URL-friendly date format\n '{{current_time}}' => date('His'), // URL-friendly time format\n '{{current_datetime}}' => date('YmdHis'), // URL-friendly date and time format\n ];\n\n // Replace each static token in the URL\n foreach ($tokens as $token => $value) {\n $url = str_replace($token, $value, $url);\n }\n\n // Check for user meta tokens and replace them - Ex: {{user_meta:is_member}}\n if (preg_match_all('/{{user_meta:(.*?)}}/', $url, $matches)) {\n foreach ($matches[1] as $index => $meta_key) {\n $meta_value = get_user_meta($user->ID, $meta_key, true);\n $url = str_replace($matches[0][$index], $meta_value, $url);\n }\n }\n\n return $url;\n }\n }\n\n // Instantiate the class\n new CustomUserRedirect();\n}\n",
"tags": [
"login",
"users",
"user roles",
"redirects",
"SnipSnip.pro"
],
"modified": "2023-08-03 19:37:26"
}
]
}
<?php
/**
* CustomUserRedirect - Redirect Users After Login [SnipSnip.pro] - https://snipsnip.pro/s/730
*/
if (!class_exists("CustomUserRedirect")) {
class CustomUserRedirect
{
// Define custom roles and rules as an associative array
private $rules = [
"subscriber" => "/series/{{username}}",
// 'contributor' => '',
// 'author' => '',
// 'editor' => '',
"administrator" => "/wp-admin/edit.php?post_type=podcast",
"default" => "/", // Default redirect for any other role
];
public function __construct()
{
// Hook the redirect function to the 'wp_login' action
add_action("wp_login", [$this, "redirectUser"], 10, 2);
}
public function redirectUser($user_login, $user)
{
// Get the user roles
$roles = $user->roles;
// Check each role and redirect accordingly
foreach ($roles as $role) {
if (array_key_exists($role, $this->rules)) {
// Replace the tokens with the actual values
$redirect_url = $this->replaceTokens(
$this->rules[$role],
$user
);
wp_redirect(home_url($redirect_url));
exit();
}
}
// If no matching role found, redirect to the default location
wp_redirect(home_url($this->rules["default"]));
exit();
}
private function replaceTokens($url, $user)
{
// Define custom tokens and their replacement values
$tokens = [
"{{username}}" => $user->user_login,
"{{user_id}}" => $user->ID,
"{{current_page}}" => $_SERVER["REQUEST_URI"],
"{{website_url}}" => get_site_url(),
"{{user_slug}}" => $user->user_nicename,
"{{referrer}}" => wp_get_referer(),
"{{user_ip}}" => $_SERVER["REMOTE_ADDR"],
"{{user_ip_hash}}" => hash("sha256", $_SERVER["REMOTE_ADDR"]),
"{{user_email}}" => $user->user_email,
"{{user_email_hash}}" => hash("sha256", $user->user_email),
"{{user_registered}}" => $user->user_registered,
"{{current_date}}" => date("Ymd"), // URL-friendly date format
"{{current_time}}" => date("His"), // URL-friendly time format
"{{current_datetime}}" => date("YmdHis"), // URL-friendly date and time format
];
// Replace each static token in the URL
foreach ($tokens as $token => $value) {
$url = str_replace($token, $value, $url);
}
// Check for user meta tokens and replace them - Ex: {{user_meta:is_member}}
if (preg_match_all("/{{user_meta:(.*?)}}/", $url, $matches)) {
foreach ($matches[1] as $index => $meta_key) {
$meta_value = get_user_meta($user->ID, $meta_key, true);
$url = str_replace($matches[0][$index], $meta_value, $url);
}
}
return $url;
}
}
// Instantiate the class
new CustomUserRedirect();
}
@brandonjp
Copy link
Author

brandonjp commented Aug 3, 2023

This is a php class I use in Wordpress to send users to specific urls after they login. Here's a quick blurb about it. But if you have any questions, comments, notice any issues, please leave a note below. You can also read more info here: https://snipsnip.pro/s/730

  • If you're using the plugin CodeSnippets.pro, then import the JSON file
  • Otherwise, open your theme's functions.php (or use another way of your choosing) and copy the PHP code

CustomUserRedirect - Redirect Users After Login [SnipSnip.pro]

  • Redirect users upon login based on their user role.
  • Easily add/remove/edit the custom roles and redirection rules and dynamic replacement {{tokens}}.
  • Include dynamic data in the redirect url, such as{{username}}, {{user_id}}, and more.
  • Supports user meta in the redirect url with {{user_meta:YOUR_META_KEY_HERE}}.

Notes: This class assumes that each user has only one role. If a user has multiple roles, they will be redirected based on the first role found in their role list. Also, be aware of privacy considerations when using tokens like {{user_email}} and {{user_ip}}, as these could potentially expose sensitive user information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment