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);
}
}