March 25th, 2009
Broken Apostrophes When Querying Wordpress Tables
I’m a big fan of the Wordpress blogging platform, and it’s the one I use when I’m setting my clients up with a blog. In most cases they want Wordpress to be a small part of their site instead of the whole thing. (You can certainly make a case for Wordpress as a full CMS, but let’s just focus on the clients who want to add a blog to their existing site.) It’s pretty easy to create a custom theme that matches their site. Copy the header. Copy the footer. Make some tweaks to style.css in the custom theme, and you’re golden. Until you try to link from the home page to a blog post with an apostrophe in the title.
If a client really understands the purpose and power of a blog, they probably won’t be content to just bury the blog on some back corner of their site. They’re going to want the latest headlines to show up on the home page. I can roll up my sleeves and write an old fashioned SQL query to pull from the Wordpress tables. In my test cases, everything works beautifully.
What I didn’t realize is that none of my test cases had apostrophes in the title. Once my client would add a post with an apostrophe, though, the headline on the home page showed a broken special character symbol. On the Wordpress pages everything looked fine.
The problem has to do with character encoding. Simple enough. I made changes in my HTML tags to use UTF8 encoding – just like Wordpress uses. That should do the trick, right? Nope. What I finally learned is that the query I was pulling out of MySQL wasn’t UTF8 encoded. So the information I was getting already had broken characters before the encoding that I set in HTML was applied.
It’s a little confusing. (Heck I’m not sure I entirely understand.) But here’s the important part: If you’re getting broken apostrophes when you pull information out of a Wordpress table, include this line right after you call mysql_connect().
mysql_query(“SET NAMES ‘utf8′”);
That’s what did the trick for me.




Mar 25th, 2009
11:48 pm
Thanks for this excellent tip and your timing couldn’t be better! I just finished a Wordpress blog for a client and they have realized they would really like the headlines as part of the main site. I was planning to start on the SQL this weekend. Character encoding would not have been my first thought for sure. Thanks again!
Apr 28th, 2010
2:22 am
Nice site and topic. Anyway thanks for the information it’s the SQL Statement based on my experienced on Visual Basic Programming and better avoid apostrophes.
Regards,
Kenneth