Advertisement
SimeonGriggs

strip tags on post save

Jun 21st, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.38 KB | None | 0 0
  1. function strip_tags_on_post_save($post_id)
  2. {
  3.     // If this is a revision, get real post ID
  4.     if ($parent_id = wp_is_post_revision($post_id)) {
  5.         $post_id = $parent_id;
  6.     }
  7.  
  8.     // Get post content
  9.     $post_object = get_post($post_id);
  10.  
  11.     // Check if this post has content
  12.     if (!empty($post_object)) {
  13.         // unhook this function so it doesn't loop infinitely
  14.         remove_action('save_post', __NAMESPACE__ . '\\strip_tags_on_post_save');
  15.  
  16.         // Get just the post content
  17.         $content = $post_object->post_content;
  18.  
  19.         // Keep just these tags
  20.         $allowed_html = array(
  21.             'a' => array(
  22.                 'href' => array(),
  23.                 'title' => array()
  24.             ),
  25.             'br' => array(),
  26.             'em' => array(),
  27.             'i' => array(),
  28.             'strong' => array(),
  29.             'b' => array(),
  30.             'img' => array(),
  31.             'ul' => array(),
  32.             'ol' => array(),
  33.             'li' => array(),
  34.             'blockquote' => array(),
  35.             'hr' => array(),
  36.         );
  37.  
  38.         // Do it.
  39.         $content_stripped = wp_kses($content, $allowed_html);
  40.        
  41.         // Update the post, which calls save_post again
  42.         wp_update_post(array( 'ID' => $post_id, 'post_content' => $content_stripped ));
  43.     }
  44. }
  45. add_action('save_post', __NAMESPACE__ . '\\strip_tags_on_post_save');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement