1

I've a custom Post Type i.e. prj and need to auto increment it's post_title (title) and post_name (slug) on post save, update regardless of the post status .. the post can never be deleted that's why it won't be an issue ..

Need it to behave just like AutoIncrement field in SQL .. once an ID is assigned, it should never be replicated ..

So far, I've reached to the code mentioned below .. but the problem is it is only setting up the post title, not the slug and the increment feature is not working as well ..

add_filter( 'wp_insert_post_data' , 'odin_prj_title' , '99', 2 );
function odin_prj_title( $data , $postarr )
{
    if( $data['post_type'] == 'prj' ) {
        $last_post = wp_get_recent_posts( '1');
        $last_post_ID = (int)$last_post['0']['ID'];
        $data['post_title'] = 'P0' . ($last_post_ID + 1);
    }
    return $data;
}
1

I did not work it out using save_post or any other save-filter, so as I am only needing to do the same for the title, I used the default_title filter. This means that it works for drafts as well.

add_filter( 'default_title', 'change_title', 10, 2 );
function change_title( $title, $post ) {
    return 'PO' . $post->ID;
}

Notice that here I am using the newly created post's ID, so I don't have to fetch $last_post_id as you do, and perhaps you don't have to do that either if you do it like this. Remember to check the post type before changing the title though.

I have not tested to do the same with the slug, but I noticed there is a similar filter for the slug, called wp_unique_post_slug. Hopefully this will help you. :)

Edit: here is the filter from WP Core code, https://developer.wordpress.org/reference/functions/wp_unique_post_slug/

  • This is not a solution to my question! – Hassan Alvi Mar 2 '18 at 14:03
  • @HassanAlvi okey, sorry to hear that. I am incrementing my titles using the default_title filter just like this, so that is why I thought it would work for you too. – Magnetize Mar 2 '18 at 14:11
  • any other solution? – Hassan Alvi Mar 5 '18 at 15:15
  • No, not at the momemt I'm afraid, sorry. :( – Magnetize Mar 6 '18 at 13:25
  • 1
    yes .. already done that! :) – Hassan Alvi Mar 12 '18 at 14:18
1

I figured out using wp_count_posts function, I can get the last total number of posts and save the title at run-time! Added a bit of conditions as well ..

add_filter( 'wp_insert_post_data' , 'odin_prj_title' , 10, 2 );
function odin_prj_title( $data , $postarr )
{
    if( $data['post_type'] == 'prj' && $data['post_status'] != 'publish' ) {
        $count_posts = wp_count_posts('prj');
        $published_posts = $count_posts->publish;
        $data['post_title'] = 'P0' . ($published_posts + 1);
    }
    return $data;
}

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.