Skip to content

Instantly share code, notes, and snippets.

@tlehtimaki
Last active September 14, 2018 18:45
Show Gist options
  • Save tlehtimaki/c0d9092441f6585a7c7209df9fedd32b to your computer and use it in GitHub Desktop.
Save tlehtimaki/c0d9092441f6585a7c7209df9fedd32b to your computer and use it in GitHub Desktop.
Build WordPress post_title from post related metadata
<?php
/**
* Assign name as title before save when post type is company_personnel.
*
* Instruction of use:
* ------------------
* you can place this eg. in your themes functions.php
*
* Use case:
* --------
* You could use this with custom post type,
* where you only want to set title programmatically.
* Not via the Graphical User Interface.
*
* @author Toni Lehtimäki
*
* @param array $data
* @param array $postarr
*
* @return array $_data array of post values to be saved to database
*/
function my_personnel_set_name_as_title( $data, $postarr ) {
$_data = $data;
// Change title if post type is company_personnel.
if ( $_data['post_type'] === 'company_personnel' ) {
// Prepare for renaming the post title
$_post_meta = get_post_meta($postarr['ID']); // Get the post metadata.
$fname = esc_attr($_post_meta['company_person_firstname'][0]); // Get the first name from meta.
$lname = esc_attr($_post_meta['company_person_lastname'][0]); // Get the last name meta.
$new_title = $lname . ', ' . $fname;
// Prepare for changing the post slug
$post_slug = sanitize_title_with_dashes ($new_title,'','save');
$post_slug_sanitized = sanitize_title($post_slug);
// Set the post title only when the existing one is not equal.
if ( $postarr['post_title'] !== $new_title ) {
$_data['post_title'] = $new_title;
$_data['post_name'] = $post_slug_sanitized;
}
}
return $_data;
}
add_filter( 'wp_insert_post_data', 'my_personnel_set_name_as_title', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment