Page 1 of 1

WordPress – Preserve Backslash in Posts

WordPress – Preserve Backslash in Posts
   16

Preserve backslashes in WordPress brings us to one of the annoying features of WordPress: it strips backslashes.
It has it’s place an reason of course, but it can be a PITA when you’re trying to post code examples.

In this very short article, I’ll show you how to preserve your backslashes with a very small function which replaces each backslash with an HTML entity, which should make it safe to work with in your database and not loose the backslash. Even my code highlighter does not seem to be bothered by it and displays the code correctly (ie. not showing the HTML entity, but rather show the desired backslash).

Note that manually entering the HTML entity in the HTML code of your article (Text view) works only once! When loaded again in the tinyMCE editor, the HTML entity will be converted to a backslash again and posting an update would remove that backslash again. This function prevents the loss of the backslash by doing it’s work each time you save your work.




Preserve Backslash by using HTML Entity

This function is ridiculously simple, and it works great on my own websites.

This is what it does:

When a post is being submitted (new, updated, etc), this function is being called and replaces ALL occurrences of a backslash (\) with it’s HTML entity counter part, which is “#&92; ” (see also our ASCII HTML Table).

The post will be updated and WordPress will strip all backslashes, but not the HTML entities.

When opening the post again for editing, you’ll see the backslashes are there as regular backslashes.

When posting an update, the cycle repeats.

If anyone feels this is bad, wrong or unsafe: please feel free to comment and help us improve!

My Function to Preserve BackSlash

Add the following code to the functions.php file of your active theme.

Please make sure that it’s before any other add_action('save_post', 'somefunction' ); calls in your functions.php. So any “add_action” call with “save_post” in it. Otherwise the backslashes will still be stripped before WordPress gets to your new function and this trick will not work!

If unsure; paste it way in the beginning of your functions.php (after a possible “<?php” of course) – and keep in mind: your file might not have such a call yet.

Note that this post is already prove that it works, plenty of backslashes in this post that stay … 

Caution … 

In line 5, replace the quoted single backslash '\'  with ‘&#92;’ (single quotes included).
Unfortunately, the code highlighter or content management system keeps replacing it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// T4A Preserve Backslashes in posts

function t4a_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', 't4a_keepbackslash' );

    $UpdatedPost = array (
          'ID'           => $PostID,
          'post_title'   => $thePost->post_title,
          'post_content' => $Content
        );
   
    wp_update_post( $UpdatedPost );
       
    // re-hook this function
    add_action( 'save_post', 't4a_keepbackslash' );
}

add_action('save_post', 't4a_keepbackslash' ); // Update Content when saving content

 

Support Us ...


Your support is very much appreciated, and can be as easy as sharing a link to my website with others, or on social media.

Support can also be done by sponsoring me, and even that can be free (e.g. shop at Amazon).
Any funds received from your support will be used for web-hosting expenses, project hardware and software, coffee, etc.

Thank you very much for those that have shown support already!
It's truly amazing to see that folks like my articles and small applications.

Please note that clicking affiliate links, like the ones from Amazon, may result in a small commission for us - which we highly appreciate as well.

Comments


There are 16 comments. You can read them below.
You can post your own comments by using the form below, or reply to existing comments by using the "Reply" button.

  • Aug 25, 2018 - 12:55 AM - Rich - Author: Comment Link

    Thanks for this.  I’m going to test and implement it and eventually roll it into a plug-in for future use… after I go and fix 10 years worth of posts on my tech blog that contained plenty of backslashes at one point.  Argh!

    Reply

    Rich

    • Aug 26, 2018 - 4:43 AM - hans - Author: Comment Link

      Hi Rich!

      Glad it’s been of use for you. I know _exactly_ what you mean with cleaning up years of code … it sucks.
      If you ever get to create such a plugin; please feel free to post a link here! 

      Reply

      hans

  • Aug 25, 2018 - 1:00 AM Comment Link
    PingBack: techish.net

    […] update 2:  found this article that creates a function to convert backslashes into HTML entities as the posts are saved.  https://www.tweaking4all.com/web-development/wordpress/preserve-backslash-in-posts/#comment-268277 […]

  • Aug 28, 2018 - 8:40 AM Comment Link
    PingBack: techish.net

    […] Code Credit: Tweaking4All.com […]

  • Dec 1, 2022 - 4:25 AM - Paul Cobben - Author: Comment Link

    When I add the above code to my functions.php of my child theme it gives errors

    First on line 7. After removing the ‘ line 7 is ok

    Then on line 8

    The error is: syntax error, unexpected identifier “save_post”, expecting “)”

    Reply

    Paul Cobben

    • Dec 1, 2022 - 6:55 AM - Hans - Author: Comment Link

      Hi Paul,

      thanks for reporting.

      The quote in line 7 should be completely ignore in your PHP file, since it is a comment only.
      You can remove line 7 all together, but it does make me wonder if there is something else going wrong.
      I’m guessing something is going wrong with copy and pasting the code (specifically line 5).

      Note: “save_post” is a legit WordPress hook, but I would not expect PHP to return an error, even if it did not exist. I could be wrong though, it’s been a while I worked with PHP.

      I’m posting the code here again, maybe copy/paste this to see if it makes a difference?
      I have seen before, with certain browsers under Windows, that copy and paste sometimes comes with unexpected results (like replacing quotes with different quotes and end-of-line characters being different etc).

      // T4A Preserve Backslashes in posts
      function t4a_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', 't4a_keepbackslash' );
          $UpdatedPost = array (
                'ID' => $PostID,
                'post_title' => $thePost->post_title,
                'post_content' => $Content
              );
         
          wp_update_post( $UpdatedPost );
             
          // re-hook this function
          add_action( 'save_post', 't4a_keepbackslash' );
      }
      add_action('save_post', 't4a_keepbackslash' ); // Update Content when saving content

      Hope this helps.

      Reply

      Hans

      • Dec 1, 2022 - 7:25 AM - Paul Cobben - Author: Comment Link

        Thanks for your quick reply, but it has the exact same result as earlier.

        The line     remove_action( ‘save_post’, ‘t4a_keepbackslash’ );        gives the error:     syntax error, unexpected identifier “save_post”, expecting “)”

        Reply

        Paul Cobben

      • Dec 1, 2022 - 7:33 AM - Hans - Author: Comment Link

        For some reason (and I suspect line 5) PHP is reading this wrong.

        Try this (note how I changed line 5):

        function t4a_keepbackslash($PostID) {
            $thePost = get_post($PostID);
            $Content = str_replace('\\', '&#92;', $thePost->post_content);
                
            // unhook this function so it doesn't loop infinitely
            remove_action( 'save_post', 't4a_keepbackslash' );
            $UpdatedPost = array (
                  'ID' => $PostID,
                  'post_title' => $thePost->post_title,
                  'post_content' => $Content
                );
            
            wp_update_post( $UpdatedPost );
                
            // re-hook this function
            add_action( 'save_post', 't4a_keepbackslash' );
        }
        add_action('save_post', 't4a_keepbackslash' ); // Update Content when saving content

        Please let me know if this worked so I can update the code here.

        Reply

        Hans

        • Dec 1, 2022 - 8:36 AM - Paul Cobben - Author: Comment Link

          The error is gone now, but my backslashes are still gone after publishing a post.

          Reply

          Paul Cobben

  • Dec 1, 2022 - 8:01 AM - Paul Cobben - Author: Comment Link

    The error is gone now, but my backslashes are still gone after publishing a post.

    Reply

    Paul Cobben

    • Dec 1, 2022 - 8:46 AM - Hans - Author: Comment Link

      I do not know what to tell you … 
      Did some tests on my own website, and both codes just works.
      Running WordPress 6.1.1 with PHP 7.4 on a Linux server.

      Could it be that your functions.php is being cached?

      Reply

      Hans

      • Dec 1, 2022 - 8:53 AM - Paul Cobben - Author: Comment Link

        Hi Hans,

        Maybe the difference is that I use the latest stable version of PHP 8.0?

        Reply

        Paul Cobben

      • Dec 1, 2022 - 9:19 AM - Hans - Author: Comment Link

        That is not impossible of course – although I’de be surprised if PHP 8.x would affect this.
        On that note: I’m always super weary about upgrading PHP to a next level – I’ve seen too many glitches over time. Migrating from 6.x to 7.x was already a drama.

        Now, Googling “save_post” and “PHP 8” didn’t bring any shocking info that may point to this though.

        Unfortunately, I am not yet able to switch to PHP 8 on my test setup.
        They want me to pay $60 to upgrade to a new MAMP version and since I test some PHP code maybe once or twice a year, I’m not (yet) prepared to pay that 

        Considering that big steps in PHP usually come with some big programming changes, maybe try if this function is being called by doing something goofy like replacing line 5 with:

        $Content = str_replace('\\', '******', $thePost->post_content);

        Just so you see very clearly something happened in your code.

        If that doesn’t work, add something unusual to your post, for example “banana” and see if it replaces that by replacing line 5 with:

        $Content = str_replace('banana', '******', $thePost->post_content);

        Just for testing purposes of course.

        Reply

        Hans

        • Dec 1, 2022 - 9:36 AM - Paul Cobben - Author: Comment Link

          Hi Hans,

          Clear, thanks for your solution and support. I will look further into it, and when I have a solution, I will post it here.

          Kind Regards,

          Paul Cobben

          Reply

          Paul Cobben

          • Dec 1, 2022 - 11:21 AM - Paul Cobben - Author: Comment Link

            I have disabled my WPUF plugin and post directly with your updated script (nr 2) and now it works.

            With the WPUF plugin enabled I will  have to change it within when that plugin submits.

            Paul Cobben

          • Dec 1, 2022 - 11:31 AM - Hans - Author: Comment Link

            Nice find – good to hear you found what is causing this, and thank you very much for sharing! 
            That may be tricky to find a fix for that though. I have never used WPUF, but at least you now know who to contact. 

            Hans



Your Comment …

Do not post large files here (like source codes, log files or config files). Please use the Forum for that purpose.

Please share:
*
*
Notify me about new comments (email).
       You can also use your RSS reader to track comments.


Tweaking4All uses the free Gravatar service for Avatar display.