How to retrieve category NAME instead of ID in a function with a taxonomy custom field?

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

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?

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply