I am using the Advanced Custom Fields plugin, which is very good.
I am trying to take the output of one of the fields I created and give it the “permalink treatment”, that is strip out non-alphanumeric characters like slashes, convert uppercase to lowercase, and convert spaces to dashes.
Specifically I am wanting to do this with the checkbox field. I want to do this, because I want to use the outputted values as css class names.
Its output is called by this bit of PHP (modified slightly from the documented use, see example #4):
<?php
$values = get_field('field_name');
if($values)
{
foreach($values as $value)
{
echo ' ' . $value;
}
}
?>
Which returns all of the checkbox values (5 – 10 in this case) separated by a space. I successfully got the values showing up as class names, but now I need a way to format them to actually work as class names.
How could I tweak this to work? I found this bit that seems to work for a sinlge string:
function stripJunk($string){
$string = str_replace(" ","-", trim($string));
$string = preg_replace("/[^a-zA-Z0-9-]/","", $string);
$string = strtolower($string);
return $string;}
but in my case it’s an array, and I don’t know how to work with that. I’m pretty worthless when it comes to PHP, except for being able to tweak things a little bit without breaking it.
You could use
sanitize_html_class()
orsanitize_title_with_dashes()
. Both functions do almost the same. But note that much more characters a valid in CSS class names.Examples: â â ââ½ â¾ â¿ â â ⤠⦠â â â â â« â» â¥
Update
I recommend to encapsulate the code in a prefixed function to avoid collisions with poorly written plugin using the same names as you do.
Example (not tested):
And when you need the CSS classes somewhere just write:
I couldn’t test the code code: I don’t have the plugin installed, and my main computer is broken, so there may be errors. Feel free to edit this post and fix the broken code. 🙂