I’m trying to change the post title (both back-end and front-end) for a specific post type through custom field. The custom field I’m using is a taxonomy field where you I choose from different categories (cars). I’m using this code:
//Save ACF field as post_content for back-end
add_action('save_post', 'change_title_cars');
function change_title_cars($post_id) {
global $_POST;
if('cars'== get_post_type())
{
$post_custom_title = get_post_meta($post_id,'car_name',true);
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $post_custom_title;
remove_action('save_post', 'change_title_cars');
wp_update_post( $my_post );
add_action('save_post', 'change_title_cars');
}
}
//Save ACF field as post_content for front-end
add_action('acf/save_post', 'change_title_frontend_cars');
function change_title_frontend_cars($post_id) {
global $_POST;
if('cars'== get_post_type())
{
$post_custom_title = get_post_meta($post_id,'car_name',true);
$my_post = array();
$my_post['ID'] = $post_id;
$my_post['post_title'] = $post_custom_title;
remove_action('acf/save_post', 'change_title_frontend_cars');
wp_update_post( $my_post );
add_action('acf/save_post', 'change_title_frontend_cars');
}
}
And it works fine, except that it shows the category ID (number) in the title instead of the name.
I tried changing Return Value in the custom field setting from Term ID to Term Object, but it didn’t work.
Note: The value of (taxonomy custom field) is also the post category.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You need to get the term object first.
//Your meta field $post_custom_title = get_post_meta($post_id,'car_name',true); //Get the term object by id. change taxonomy_slug to the taxonomy you intend to use $term = get_term_by( 'id', $post_custom_title, 'taxonomy_slug' ); //Retrive the term name and use it as post title $term_name = $term->name; //call the wp_update_post function setting $term_name as the post title.
Just curious, why would you want to set a common title for all those posts belonging in the same term?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0