Last active
August 18, 2024 12:00
-
-
Save philhoyt/11ab22518aa26fedeb89867a228ea53f to your computer and use it in GitHub Desktop.
Using Advanced Custom Fields to create your Post Title
This file contains 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 | |
/** Create Title and Slug */ | |
function acf_title( $value, $post_id, $field ) { | |
if ( get_post_type( $post_id ) === 'staff' ) { | |
$new_title = get_field( 'first_name', $post_id ) . ' ' . $value; | |
$new_slug = sanitize_title( $new_title ); | |
wp_update_post( | |
array( | |
'ID' => $post_id, | |
'post_title' => $new_title, | |
'post_name' => $new_slug, | |
) | |
); | |
} | |
return $value; | |
} | |
add_filter( 'acf/update_value/name=last_name', 'acf_title', 10, 3 ); |
I adapted this to my use case, and the title only updated if I updated the post twice.
I modified the code (changing $new_title = $value) and it updates the title after updating the post once , though I'm not sure why it works. If someone more experienced than me could explain why it works, or a better way to do it I would appreciate it!
`function review_title( $value, $post_id, $field ) {
if ( get_post_type( $post_id ) === 'review' ) {
$new_title = $value;
$new_slug = sanitize_title( $new_title );
wp_update_post(
array(
'ID' => $post_id,
'post_title' => $new_title,
'post_name' => $new_slug,
)
);
}
return $value;
}
add_filter( 'acf/update_value/name=reviewer_name', 'review_title', 10, 3 );`
This works for me:
function acf_title_solicitudes( $value, $post_id, $field ) {
$new_title = get_field('servicio', $post_id). ' ' . $value;
$slug = sanitize_title( $new_title );
$postdata = array(
'ID' => $post_id,
'post_title' => $new_title,
'post_type' => 'solicitudes',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=servicio', 'acf_title_solicitudes', 10, 3);
Source: https://www.jennybeaumont.com/auto-create-post-title-acf-data/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To get "Last Name, First Name" here's the code: