WordPress – Adding post category requires page refresh to show up

I’m developing a plug-in and today, after a bunch of refactoring, found myself not able to add a category or tag to a Post and have it show in the list (as in this sort of screen):

 

If found the guiding answer at on StackOver at https://stackoverflow.com/a/50656747/115704 and while I also provided the following as an answer on that post I find the moderators on StackOverflow to overzealous pricks and likely to screw with my contributions, so I’m recording it here as well.

The cause

The ultimate cause is white space in PHP files appearing before the opening and closing of PHP code.

Finding the culprit is the hard part and that where I might be able to help.

 

What I said

I experienced this issue today, and white space in PHP files was the problem.

However, I want to share the steps I took to resolve the issue:

  1. I tried opening every PHP file and checking for blank lines at the start and end of the file. I picked up a few problems but the issue persisted.
  2. I was also able to do a regex search in my IDE for problems. I used Textmate/Regex: Strip whitespace from beginning/end of file as a reference point and [without quotation marks] the following regex searches “https://regex101.com/r/5EExaF/1” to find space/blank lines at the end of a file, and “https://regex101.com/r/qs17J9/1” for the start of a file.
  3. There were still problems so I narrowed down the scope by disabling plug-ins (I also knew it was one of my own plug-ins in the site I’m developing, so that made it easier).
  4. Re-activating a plug-in give a warning “The plugin generated X characters of unexpected output during activation”. This helped me in the trial-and-error process of narrowing down the source.
  5. Once I had the plug-in identified, I started commenting out require_once() calls in PHP files until the “The plugin generated X characters of unexpected output” warning disappeared.
  6. Eventually, I realised I’d broken the plug-in during refactoring and was doing a require_once() on a PHP file that was pure HTML (to inject favicon tags into a page header) rather than the appropriate add_action() call on the file as I originally intended.

Hopefully, these debug steps provide some inspiration to other people suffering the same problem. As far as I know, WordPress does not offer any easy way to identify the cause of this problem (i.e. it does not identify which file has bad spaces in it).

NOTE: I had to link to regex101 to shoe the actual values because WordPress or WordFence seems to not like regex in posts.

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.