0

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.

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?

| improve this answer | |
  • Thanks it worked. As for your question, there're other custom fields, I want the title to automatically generate according to the values that have been put in these custom fields along with this one. – L. core Jul 11 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.