Yes, it’s simple – check for existence of id_valoraciones
meta value when saving post. If post does not have id_valoraciones
set, do your job with getting last value and incerementing it. If the post has id_valoraciones
meta, then – do nothing. Like this:
<?php
function auto_assign_ids( $post_id, $post, $update ) {
// Only assign ID to new approved "valoraciones" posts
if ( $post->post_status == 'publish' && $post->post_type == 'valoraciones' ) {
$id_valoraciones = get_post_meta( $post_id, 'id_valoraciones', true );
if( ! $id_valoraciones ) {
// get the most recent "valoraciones" posts
$valoracion_args = array(
'numberposts' => 2,
'post_type' => 'valoraciones',
'orderby' => 'post_date',
'order' => 'DESC'
);
$valoraciones = get_posts( $valoracion_args );
// get the id_valoraciones of the prior post
$last_id = get_post_meta( $valoraciones[1]->ID, 'id_valoraciones', true );
// increment
if ( !$last_id ) {
$last_id = 0;
}
$last_id++;
update_post_meta( $post_id, 'id_valoraciones', $last_id );
} else {
// id_valoraciones was set before
}
}
}
add_action( 'save_post', 'auto_assign_ids', 100, 3 );
By the way, remove_action
part of your code is useless, update_post_meta
does not trigger save_post
hook, it’s used when wp_insert_post()
ing inside save_post
hook.