Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created March 31, 2020 17:33
Show Gist options
  • Select an option

  • Save morgyface/0061c9bb5bdd1a5065bd143e5ba6b541 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/0061c9bb5bdd1a5065bd143e5ba6b541 to your computer and use it in GitHub Desktop.
WordPress | Get names
<?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;
}
@morgyface
Copy link
Author

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:

    $post_title = get_the_title();
    $names = get_names($post_title);
    $first_name = $names['first'];
    $last_name = $names['last'];
    <p>First name: <?php echo $first_name; ?></p>
    <p>Last name: <?php echo $last_name; ?></p>

This code would typically go in your single.php template.

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.

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