0

I need to add incrementing id only for published posts. I try to make it when saving posts with add_post_meta function. But it always returns 1.

add_action('publish_post', 'add_program_id_automatically');
function add_program_id_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        $posts_table = $wpdb->prefix."posts"; 
        $last_post = $wpdb->get_row("SELECT MAX(ID) FROM $posts_table WHERE post_type = 'post' AND post_status = 'publish'",ARRAY_A);
        $program_id = (int)get_post_meta($last_post['MAX(ID)'], 'program_id', true) + 1;
        add_post_meta($post_ID, 'program_id', $program_id);
    }
}
www
  • 35
  • 7
  • Wouldn't the post that is currently being published usually be the one with the highest ID, thus not having the Meta field, and so getting 0 + 1 =1? What exactly are you trying to achieve? Maybe there is a simpler/clewaner way. – janh Nov 24 '17 at 22:53
  • Thanx! I want add extra ID to every published post. It will display on webpage. Also it can be changed in admin panel. And this ID should be created automatically when I publish new post. If last publish post has 'program_id' = 3, new publish post should have 'program_id' = 4, etc. And now I understand why my code does not work. – www Nov 25 '17 at 08:00

0 Answers0