I want to write the post title with the content of a custom field $sentence_number, this way:

add_action('save_post', function ($title, $post_id) {
    $post_type = get_post_type($post_id);
    if ($post_type == 'sentence') {
        $sentence_number = get_field('sentencia_no', $post_id);
        wp_update_post($post_id, [
            'post_title'   => $sentence_number
}, 10, 2);

But I get this error:

Uncaught Error: Maximum function nesting level of '200' reached, aborting!

How should I do it for avoid the loop? Thank you.

  • You use wp_update_post inside your action callback. It calls save_post so you get infinite loop ;) – Krzysiek Dróżdż Jul 28 '18 at 12:39
  • Understood. Thank you. What is the right way to do it? – aitor Jul 28 '18 at 12:47

There is a simple way, You need to use filter hook wp_insert_post_data So the code should be like

add_filter( 'wp_insert_post_data', 'set_post_title_with_field_value' );

function set_post_title_with_field_value( $data )
    if ($data['post_type'] == 'sentence' ){
        $sentence_number = get_field('sentencia_no', $data['ID']);
        $data['post_title'] = $sentence_number;
    return $data;

You need to add this code into theme's functions.php. So try the code and let me know the result. Thanks

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.