How to auto update post title and slug with category name when post status is updated

I need to auto update post title and slug with category name every time when post status is updated. Some function like this but with the correct code....

add_filter('wp_insert_post_data','reset_post_date',99,2);
   function reset_post_date($data,$postarr) {

   $data['post_title'] = How to add category name here?

 //also update the slug of the post for the URL
     $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );
     return $data;
  }

EDIT

I tried by myself but without success. Now I'm trying to run this function only when status is changed from draft to publish...but again no success.

add_filter( 'the_title', 'my_modify_title', 10, 2 );
 function my_modify_title( $title, $id ) {
  if( in_category( 'My Category', $id ) ) {
   $title = 'My Category';
 }
  if( in_category( 'New Category', $id ) ) {
   $title = 'New Category';
 }
return $title;
}

and

add_action('draft_to_publish', 'my_modify_title', 10, 2);

how to add filter and action in one function to make it work together?

Topic title slug categories Wordpress

Category Web


You need post status transitions, and quite similar with this post:

only what you need to do update post title and slug, and this is easy.

Update post examples


Since you wrote like this:

add_filter( 'the_title', 'my_modify_title', 10, 2 );
 function my_modify_title( $title, $id ) {
  if( in_category( 'My Category', $id ) ) {
   $title = 'My Category';
 }
  if( in_category( 'New Category', $id ) ) {
   $title = 'New Category';
 }
return $title;
}

Note that codex is saying 'the_title' should work only inside the loop. I would never update slugs inside loop. The loop looks to me more like a way to draw the post content.

Also note, if trying to update the title:

$title = $title. "My Category";

would be more common.

What I would suggest:

add_action('draft_to_publish', 'my_modify_title', 10, 2);
function my_modify_title ($post){
   // your work to update post slug and title.

    $current_title = $post->post_title;
    $current_slug = $post->post_name;

    $new_slug = ...;
    $new_title = ...;



    wp_update_post(
        array (
            'ID'        => $post->ID,
            'post_name' => $new_slug, 
            'post_title'=> $new_title
        )
    );

   return;    
}

And you have the last code inside your functions.php or some even better place.

Check out this ref:

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.