-1

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?

1
  • then you need to learn "how to get category name ?"
    – Jevuska
    Commented Mar 10, 2016 at 0:33

1 Answer 1

0

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:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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