Recently built a client website and was pulling in a custom excerpt to the homepage for a custom post type. Everything worked fine until the client decided they were going to add a header image above every post and add some returns before the actual text started. This change on their end started giving my custom excerpt 3 space in front of the custom excerpt.
Here was my quick code to create a quick custom excerpt.
substr(get_the_excerpt(), 0, 85)
The above code I am using the PHP fucntion of substr and passing in the WordPress function get_the_excerpt(), and limiting to 85 characters.
Now my first instinct to fix this white space issue was to run a PHP function of trim on the output, this would get rid of all white spaces as well as any line breaks, but it wouldn’t work! So I tried a couple other methods of trim like, ltrim and rtrim, again wasn’t working! Spent like an hour trying to figure out what the heck was going on. Then I found on some WordPress board you can NOT modify the excerpt! Finally after trying a few other things out I got something to work.
echo str_replace(' ', '', substr(get_the_excerpt(), 0, 85));
Replacing the   as that was the code that was creating the spaces in the content section of the custom post type.
I am really hoping if you come across the same problem you will find this blog post to save you about an hour of trouble. Because I couldn’t find much on Google about how to trim white space on the WordPress excerpt! Except of course from the people that like to write 50 lines of code for something you can do in one line. Like my above solution 🙂