0

I wrote a little bit of code to update the post name and slug (of my cpt) when saving. This is working nice when I update a post.

I just noticed theses few lines are affecting the creation and deletion of posts.

When I click to delete a post, a message appears and says the post has been deleted but it's not. It's always on my dashboard.

When I create a new post, I also get a successful message but the post isn't created.

When I remove this code, the add and delete is working.. So I think this hook cause something wrong.

function rohs_update_title($post_ID){
    $post_type = get_post_type($post_ID);

    // If this isn't a 'rohs_menu' post, don't update it.
    if ( "rohs_menu" != $post_type ) return;

    $postAuthorId = get_post_field( 'post_author', $post_ID ); // get the post author ID

    $userToGetData = 'user_'.$postAuthorId;
    $restaurantName = get_field( 'nom_restaurant', $userToGetData );
    $date = get_field('date');

    remove_action( 'save_post', 'rohs_update_title' );

    $menuName = 'Menu du '.$date.' chez '.$restaurantName;  
    wp_update_post( array( 'post_id' => $post_ID, 'post_title' => $menuName, 'post_name' => sanitize_title($menuName)) );

    add_action( 'save_post', 'rohs_update_title' );
}
add_action( 'save_post', 'rohs_update_title', 10, 3 );

get_field is form acf

0

There are something wrong in your code, Here I edited what you tried,

function rohs_update_title($post_ID){

$post_type = get_post_type($post_ID);

// If this isn't a 'rohs_menu' post, don't update it.
if ( "rohs_menu" != $post_type ) return;

$postAuthorId = get_post_field( 'post_author', $post_ID ); // get the post author ID

$userToGetData = 'user_'.$postAuthorId;
$restaurantName = get_field( 'nom_restaurant', $userToGetData );
$date = get_field('date');

remove_action( 'save_post', 'rohs_update_title' );

$menuName = 'Menu du '.$date.' chez '.$restaurantName;  
wp_update_post( array( 'ID' => $post_ID, 'post_title' => $menuName ) );

add_action( 'save_post', 'rohs_update_title' );
}
add_action( 'save_post', 'rohs_update_title', 10, 1 );

Now try this and let me know

  • Thanks for your reply. I changed 'post_id' => $post_ID to 'ID' => $post_ID. It work's. I don't know where I found 'post_id' but that looks wrong. You also changed 10, 3 to 10, 1. Does it change something ? Can you please explain Thanks – Steven Roh Oct 11 '17 at 14:11
  • Yes, I changed it, since there is no means to set 3 where you are using only one argument '$post_id' – Jaed Mosharraf Oct 11 '17 at 14:13

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.