• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP Bitz

A curated collection of code snippets for WordPress

  • Home
  • About
  • Blog
  • Code Snippets
You are here: Home / Code Snippets / Get email domain from a user’s email

Get email domain from a user’s email

April 15, 2021

// Verbose example to show steps:
$user_email   = "example@domain.com";
$email_array  = explode( "@", $user_email );
$email_domain = array_pop( $email_array );
echo $email_domain; // Will output "domain.com"


// Simple one line, get domain from email:
$domain = array_pop( explode( "@", $user_email ) );


/**
 * Here's a more detailed example of getting a user's email 
 * and then extracting the domain in WordPress. (assumes 
 * you have the user ID in $user_id).
 * 
 * @uses get_user_by()
 */
$user = get_user_by( 'ID', $user_id );
$user_email = $user->user_email;
$domain = array_pop( explode( "@", $user_email ) );


/**
 * Similar WP example to handle getting the email domain
 * when the user registers (assumes default WP reg form).
 */
 $user_email = sanitize_email( $_POST['user_email'] );
 $domain = array_pop( explode( "@", $user_email ) );
 
 

Chad Butler

Primary Sidebar

Join for free!

Get free code snippets, WordPress best practices, and practical Content Marketing advice from seasoned WordPress expert Chad Butler (butlerblog):

Recent Posts

  • How to Run WP-CLI on Windows
  • Get an array of variation IDs for a WooCommerce product
  • Check and delete orphaned post meta in WordPress
  • Block an IP address from accessing your site
  • Using WordPress Debug Constants

Copyright © 2022 · Maker Pro on Genesis Framework · WordPress · Log in