Creating function to replace post title not working Creating function to replace post title not working wordpress wordpress

Creating function to replace post title not working


if ( get_post_status( $post_id ) === FALSE ) {    wp_update_post( $my_post );}

Can't ever happen. If false is being returned, it means post doesnt exist. You can't really update a post that doesn't exist. Check source code of the function.

There are few ways, I think, to get your task done but I'll just suggest one of them.

function title_replace_function( $post_id, $post ) {   if ( $post->post_date == $post->post_modified ) {      // code for new post   } else {      // code for edited post   }}add_action( 'publish_post', 'title_replace_function', 10, 2 );

EDIT

Alright, wasn't that easy as I thought. Here is tested, secured from infinite loops (Be aware of loops Example 1 and Example 2) piece of code, that suits your needs:

function title_replace_function( $post_id, $post ) {    if ( ! wp_is_post_revision( $post_id ) ) {        remove_action('save_post', 'title_replace_function');        if ( $post->post_date == $post->post_modified ) {            global $_POST;            $new_title_ciudad = get_field('ciudad', $post_id);            $new_title_sexo = get_field('sexo', $post_id);            $new_title_especie = get_field('especie' , $post_id);            $registered_year = date("y");            $count_mascotas = wp_count_posts('mascotas');            $next_count = $count_mascotas->publish + 1;            $new_count = sprintf("%04d", $next_count);            $new_title = "$new_title_ciudad"."$new_title_sexo"."$new_title_especie"."$registered_year"."-"."$new_count";            $my_post = array(                'ID'         => $post_id,                'post_title' => $new_title,                'post_name'  => $post_id            );            wp_update_post( $my_post );        } else {            $new_title = 'new_title';            $my_post = array(                'ID'         => $post_id,                'post_title' => $new_title,                'post_name'  => $post_id            );            wp_update_post( $my_post );        }        add_action('save_post', 'my_function');    }}add_action( 'save_post', 'title_replace_function', 10, 3 );