• I am trying to append an empty HTML tag at the end of the post content before it is saved to the database (if a new post) or updated (if an existing post). The wp_insert_post_data filter seemed like a good option, but when I tried it out I received an “Update failed” error message in the block editor.

    I’ve looked all over the forums and outside websites, but can’t seem to find a way to keep using this filter with Gutenberg. From what I’ve gathered, it has something to do with Gutenberg saving the post using the REST API. Regardless, what is a good approach to accomplish my goal?

    Here is the code I was using that kept generating the error on Publish or Update. Note that even just trying to return the content without modifying it causes the “Update failed” error message.

    
    add_filter( 'wp_insert_post_data', 'add_empty_span_tags_to_paragraph_blocks', 10, 2 );
    public function add_empty_span_tags_to_paragraph_blocks( $data, $postarr ) {
        return $data;
    }
    
    • This topic was modified 5 years, 8 months ago by korynorthrop.
Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator bcworkz

    (@bcworkz)

    No error for me on update with your example code active on my site. I recently observed similar behavior upon updates, though it appeared that the update was in fact successful. I believe a core update resolved this before I could trace the source. Be sure you have the latest version.

    If so, check again with all plugins deactivated and switch to a default twenty* theme. Temporarily place your test code in the theme’s functions.php.

    Thread Starter korynorthrop

    (@korynorthrop)

    Thanks for your reply @bcworkz. I have everything updated and have installed the twentynineteen theme and disabled all other plugins, but can only get this filter to work if I call it like so instead of calling a custom function that I declare:

    add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
       // do stuff
       return $data;
    }, 10, 2 );

    But, another thing I’m scratching my head about is that I’m seeing this hook firing three times when I update a post. If I write something to the error_log (e.g. error_log( 'post saved', 0 ); I’ll see it three times in the log file, a few seconds apart. Any ideas on what’s happening there?

    • This reply was modified 5 years, 8 months ago by korynorthrop.
    Moderator bcworkz

    (@bcworkz)

    A closure works but not a named function? A simple named procedural function and not a class method right? Just like your OP example? That is bizarre. I’ve no explanation.

    I don’t know why filters fire multiple times. They do and they have done so for a long time. It’s fallacious to assume filters only fire once per request. For typical filter use it’s of no consequence. Changing the same thing the same way 3 times has no ill effect beyond some minor inefficiencies. If your filter callback is sensitive to multiple calls for any reason, you must take measures to ensure whatever procedure is only done once despite multiple filter firings.

    One way to do so is to have your callback remove itself from the filter stack after the initial pass so it is not called again on subsequent firings. For filters use remove_filter() function.

    Thread Starter korynorthrop

    (@korynorthrop)

    Yeah the closure works, but not the named function. It’s bizarre, I’m a little baffled, but I’ll keep digging in a bit more to see if I can figure it out.

    I actually started doing exactly what you suggested with removing the callback from the filter stack after it’s called and then re-adding the filter later on. I was able to reduce the number of fires to two that way, but still trying to find the proper hook to re-add the wp_insert_post_data filter so that it doesn’t fire any additional times. However, like you said, the downside of doing a string replace a few times isn’t too awful, so I might just cut my losses and move on.

    Thanks for your feedback.

    Moderator bcworkz

    (@bcworkz)

    I’m not following why you would want to add your callback back in after removal if the goal is to not have it run more than once per request. The initial add_filter() call by itself will restart the process afresh on the next request.

    I’ll be away for a while, so don’t expect further responses from me for a while.

    I am using wp_insert_post_data() function to publish posts that are in pending post status. what i want to accomplish is increment post title on post publish. I figure it out that wp_insert_post_data will insert post data on post save and update. My problem is i want to publish post with increment post title but not on post update.

    add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );  
    function modify_post_title( $data , $postarr ) {
        
      // Check for the custom post type and it's status
        // We only need to modify it when it's going to be published
        
        $posts_status = ['publish'];
        if( $data['post_type'] == 'matrimony' && in_array($data['post_status'], $posts_status)) {
            
            $count_posts = wp_count_posts('matrimony');
        	$published_posts = $count_posts->publish;
        	$pending_posts = $count_posts->pending;
          	if ($published_posts == 0) {
                if ($pending_posts == 0) {
                    $data['post_title'] = 'ACMB' . '-1';
    		        $data['post_name'] = sanitize_title($data['post_title']);
                }
                else{
                    // Get the most recent post
                    $newposts = array(
                        'numberposts' => 1,
                        'orderby' => 'post_date',
                        'order' => 'DESC',
                        'post_type' => 'matrimony',
                        'post_status' => 'publish'
                    );
           
                    $last_post = wp_get_recent_posts($newposts);
                    $last__post_title = $last_post['0']['post_title'];
          	        $number = preg_split('/[^[:alnum:]]+/', $last__post_title);
                    $number = $number[1] + 1;
                    
                    // Save the title.
                    $data['post_title'] = 'ACMB' . '-' . $number;
    		        $data['post_name'] = sanitize_title($data['post_title']);
                }
        	} 
        	else {
    
            // Get the most recent post
            $newposts = array(
                        'numberposts' => 1,
                        'orderby' => 'post_date',
                        'order' => 'DESC',
                        'post_type' => 'matrimony',
                        'post_status' => 'publish'
                    );
           
            $last_post = wp_get_recent_posts($newposts);
            $last__post_title = $last_post['0']['post_title'];
          	$number = preg_split('/[^[:alnum:]]+/', $last__post_title);
            $number = $number[1] + 1;
            
            // Save the title.
            $data['post_title'] = 'ACMB' . '-' . $number;
    	    $data['post_name'] = sanitize_title($data['post_title']);
            
            
        }
        }
        return $data;
    }

    Above code will count posts from custom post type and find latest post by date created and increment the post title like ACMB-1,2,3…so on
    My problem is this function fires on update post which i dont want

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Modify post content before getting saved/updated in the database’ is closed to new replies.