I have a function that when you publish a news item adds a correlative ID number to it, this is it:
function update_post_id_contenido($post_id) {
$post_type = get_post_type($post_id);
if ($post_type === 'post') {
$id_contenido = get_field('id_contenido', $post_id);
if (empty($id_contenido)) {
$last_id_contenido = get_posts(array(
'post_type' => 'post',
'meta_key' => 'id_contenido',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'numberposts' => 1,
));
$last_id_contenido_value = get_field('id_contenido', $last_id_contenido[0]->ID);
if (empty($last_id_contenido_value)) {
$new_id_contenido = 1000;
} else {
$new_id_contenido = $last_id_contenido_value + 1;
}
update_field('id_contenido', $new_id_contenido, $post_id);
}
}
}
add_action('acf/save_post', 'update_post_id_contenido', 20);
What I intend is that it saves the slug so that at the end it is of the type domain.com/$id_contenido/$posttitle
I have tried this function but it returns a memory limit error.
function update_post_slug($post_id, $post, $update) {
if ($post->post_type == 'post' && $post->post_status == 'publish') {
$id_contenido = get_post_meta($post_id, 'id_contenido', true);
$post_title = sanitize_title($post->post_title);
$new_slug = $id_contenido . '/' . $post_title;
wp_update_post([
'ID' => $post_id,
'post_name' => $new_slug,
]);
}
}
add_action('save_post', 'update_post_slug', 10, 3);
You receive a memory limit error because your code triggers an infinite loop.
On
save_postyou call the functionupdate_post_slugwhich calls the functionwp_update_postwhich triggers the actionsave_post.An easy workaround to make sure the function only call once per lifetime is to have
update_post_slugunregister itself: