WP Preserve Backslashes

I created a WordPress plugin based on a personal dilemma I ran into with my site being stripped of backslashes.

Upon post save, it converts backslashes to HTML entity ] which is what will be stored in the database.

The plugin is available on GitHub at https://github.com/rjkreider/wp-preserve-backslashes
Here’s the function if you want to just drop it in your functions.php file instead of installing it as a plugin.

function wppb_keepbackslash($PostID) {
    $thePost = get_post($PostID);
    $Content = str_replace('\\', '\', $thePost->post_content);
    // unhook this function so it doesn't loop infinitely
    remove_action( 'save_post', 'wppb_keepbackslash' );
    $UpdatedPost = array (
          'ID'           => $PostID,
          'post_title'   => $thePost->post_title,
          'post_content' => $Content
  wp_update_post( $UpdatedPost );
/** if (is_wp_error($post_id)) {
 $post_id=   wp_update_post( $UpdatedPost );
        $errors = $post_id->get_error_messages();
        foreach ($errors as $error) {
                echo $error;
}   **/
    // re-hook this function
    add_action( 'save_post', 'wppb_keepbackslash' );
add_action('save_post', 'wppb_keepbackslash' ); // Update Content when saving content

Leave a Reply

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