WordPress function saves a post twice and updates all posts

I’m having a problem with a custom function. This function counts the post and assigns a number to that post. It then saves the number to a custom field and then updates the permalink to the post.

My problems are:

1). When a post is saved, it saves a post twice (Shows up as 2 revisions). I’m trying to find a way so that it saves it once.

2). I’m also trying to find a way for the function to work only once. I’m noticing that previous posts are getting edited and while they are staying the same, they do show up with lots of revisions. For example: If I have 5 posts, the first post will show up with 10 revisions.

Here’s my code:

// opens a function
function updateNumbers( $post_id ){

// sets global
global $pagenow;

// if current page is a new post and in the post CPT
if ($pagenow == ‘post.php’ && ‘post’ == get_post_type()) {

// counts all posts
global $wpdb;
$querystr = “SELECT $wpdb->posts.* FROM $wpdb->posts WHERE
$wpdb->posts.post_status = ‘publish’ AND $wpdb->posts.post_type = ‘post’ “;
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
$counts++;

// saves the number to a custom field
add_post_meta($post->ID, ‘incr_number’, $counts, true);
remove_action(‘save_post’, ‘updateNumbers’);
wp_update_post(array(‘ID’ => $post->ID,’post_name’ => get_post_meta($post->ID,’incr_number’, true)));
endforeach;
endif;
}}

// close the function and save
add_action(‘save_post’, ‘updateNumbers’);

Read more here:: WordPress function saves a post twice and updates all posts

Leave a Reply

Your email address will not be published. Required fields are marked *