Created
March 31, 2020 17:33
-
-
Save morgyface/0061c9bb5bdd1a5065bd143e5ba6b541 to your computer and use it in GitHub Desktop.
WordPress | Get names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * A function to split the post title into first and last names, | |
| * We assume everything up to the first whitespace is the first name, | |
| * the rest is considered the last name. | |
| */ | |
| function get_names( $full_name ) { | |
| if( $full_name ) { | |
| $full_name = sanitize_text_field($full_name); // remove nasties | |
| /** | |
| * For the first name we use the third parameter of strstr, | |
| * setting it to TRUE returns the part of the haystack BEFORE the first | |
| * occurrence of whitespace (excluding the whitespace). | |
| */ | |
| $first = strstr($full_name, ' ', true); | |
| /** | |
| * For the last name we use strstr in the typical way, | |
| * it returns everything after the first occurance of whitespace but | |
| * it includes the whitespace, so we use ltrim to remove it | |
| */ | |
| $last = ltrim(strstr($full_name, ' ')); | |
| $names = array( | |
| 'first' => $first, | |
| 'last' => $last | |
| ); | |
| } else { | |
| $names = null; | |
| } | |
| return $names; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WordPress function to get first and last names from a full name
I've written this as I have custom posts where the post title is the full name of the person.
At various places in the theme I only need the first or last name of the person, so we use this function to break it up.
It is used like this:
This code would typically go in your
single.phptemplate.Note: This function assumes everything after the first space is a last name, so if the person uses middle names they will be included as part of the last name too. I guess it could be made more sophisticated by counting whitespace occurrences and if two or more exist extract the characters between the first and last occurrences and set it/them as middle name(s). However this suffices for my application.