My function has a way to deal with infinite loops but causing duplicate posts
-
I have a function on my theme’s functions.php that counts the number of posts, assigns a number to a custom field and sets the slug of the post with the custom field. Problem I’m having is that I have
remove_action
thenadd_action
andadd_action
again so that I don’t have infinite loops that cause timeouts but I have double revisions and I have a plugin that copies posts to another site in my network and that does double posts on the copied site as well.This is my code:
// opens the function function updateNumbers( $post_id ){ //* Checks if the post is new or updated, if post is being updated then it skips if ( ! wp_is_post_revision( $post_id ) ){ // global wordpress database parameters and only counts posts that are published and in the 'post' CPT 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); // sets the counter at zero $counts = 0 ; // starts the loop, gets and counts how many posts are published if ($pageposts): foreach ($pageposts as $post): $counts++; // sets the number in the custom field 'incr_number' add_post_meta($post->ID, 'incr_number', $counts, true); update_post_meta($post->ID, 'incr_number', $counts); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'updateNumbers'); // update the post using the custom field in the slug, which calls save_post again wp_update_post(array('ID' => $post->ID,'post_name' => get_post_meta($post->ID,'incr_number', true))); // re-hook this function add_action('save_post', 'updateNumbers'); // close the loop endforeach; endif; // close the function and the 'if' post is an update }} // hooks into the save_post process add_action('save_post', 'updateNumbers'); // opens another call to action add_action( 'init', function() { // sets the global parameters for rewrite global $wp_rewrite; // set the permalink structure. In this example, all posts saved will be /episode/number in custom field $wp_rewrite->set_permalink_structure( '/episode/%postname%/' ); // close the action } );
Thanks for the help.
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
- The topic ‘My function has a way to deal with infinite loops but causing duplicate posts’ is closed to new replies.