Extract first word of a WordPress post title and use as a class

You want to have some individual styling for whatever reason and you need a to get the first word from a WordPress title and display it as a class. Easy. Let’s do it:

Here’s your DIV before

 

Code to Extract First Word of Title and Display It

Have a page template that is shared among a group of pages? Spiff up that page template by adding individualized classes/ids to your WordPress pages.

 

Cody By Itself

This bit of code can be used for a bit more than simply adding classes depending on your need.


Code Explanation:

What this code is doing is grabbing the title, exploding it into an array and then taking the first value of the title array and echoing the string out as lowercase.

10 thoughts on “Extract first word of a WordPress post title and use as a class

  1. Thanks for this! I put it in an archive of staff like this <a href=""> Read ‘s biography And it adds a more personal touch than just ‘read more’. Only catch is if someone’s name ends with an S you get "Read Angus’s biography" instead of Read Angus’ Biography. I’m not nearly good enough with php to know if its even possible to remove? Luckily I’m not a grammar nazi.

  2. Nice. A couple things tho’: 1) In theory, it’s possible this could generate an invalid CSS class name. 2) To be safe, this output should probably be escaped.

  3. Please Please can you help span the first word of my post title? I did that but it goes ahead to change my menu color too which i don like. if you can please i will show you the codes i used

Leave a Reply

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