Posted by on in iDevelop, PHP | 0 comments

So Corey popped a question last night in company chat room on whether WordPress has an equivalent of Rails’ to_sentence() function or not. The answer was no it doesn’t, & I thought heck that can be written quick!

Here is what I wrote quickly (and updated after that):

It can be further improved, the evaluation of three cases in switch can be removed entirely as demonstrated here.

 
Update: It seems WordPress indeed has a function for this, though its a bit obscure & the name doesn’t help either. Its wp_sprintf_l() (thanks to @mdawaffe for pointing it out) & here’s how it’ll be used.

  1. echo wp_sprintf_l( '%l', array( 'Alpha', 'Bravo', 'Charlie' ) );
  2.  
  3.  
  4. /**
  5.  * use this if you don't want Oxford commas
  6.  * eg. if you want 'Alpha, Bravo and Charlie'
  7.  * instead of 'Alpha, Bravo, and Charlie'
  8.  */
  9. function remove_oxford_commas( $separators ) {
  10.     $separators['between_last_two'] = ' and ';
  11.     return $separators;
  12. }
  13. add_filter( 'wp_sprintf_l', 'remove_oxford_commas' );

More on it here on Andy Skelton’s post who wrote it.