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.
[php]
echo wp_sprintf_l( ‘%l’, array( ‘Alpha’, ‘Bravo’, ‘Charlie’ ) );
/**
* use this if you don’t want Oxford commas
* eg. if you want ‘Alpha, Bravo and Charlie’
* instead of ‘Alpha, Bravo, and Charlie’
*/
function remove_oxford_commas( $separators ) {
$separators[‘between_last_two’] = ‘ and ‘;
return $separators;
}
add_filter( ‘wp_sprintf_l’, ‘remove_oxford_commas’ );
[/php]
More on it here on Andy Skelton’s post who wrote it.