0

I am quite new to php.

I am using advanced custom fields and have a custom field with the name tags. Users are inputting content such as:

Tag 1, Tag 2, Tag 3

I would like parse this output and show it as unordered list:

  • Tag 1
  • Tag 2
  • Tag 3

The following code gives me the field.

<div><?php the_field('tags'); ?></div>

Any suggestions, how to parse the input as an unordered list html?

I really appreciate your replies!

1

This is more about string and array manipulation with php than a WordPress related question.

The proper way to do it would be using a repeater field instead of a single text input. Advanced Custom Fields, which seems to be the plugin you are using, has a nice repeater addon. That would let the users add as many fields as they want, change their order, delete them, etcetera. All without having to worry about writing the delimiter properly.

If using the repeater field is not an option, you can use the php function explode to convert the string into an array and then process it with a simple loop.

//The custom field
$custom_field = 'Tag 1, Tag 2, Tag 3';

//Remove the extra space after the comma
$custom_field = str_replace( ', ', ',', $custom_field );

//Convert the string to array using the comma as the delimiter
$items = explode( ',' , $custom_field );

//Print the unordered list
echo '<ul>';
foreach ( $items as $item ) :
    echo "<li>$item</li>";
endforeach;
echo '</ul>';
  • Thx for your reply! How would you use this in a wordpress theme? ( I have to use it more than once) Put it in a function? I appreciate your replies – Kare Jun 12 '16 at 21:02
  • Yes, it can be a function. You can pass the string $custom_field as an argument like function echo_tags_as_list( $custom_field ) { ... } and then call it like echo_tags_as_list( 'Tag 1, Tag 2, Tag 3' ). – Luis Sanz Jun 12 '16 at 21:18
  • I am not very into php atm. Would you be so kind to show me how to function looks like? I appreciate your reply! – Kare Jun 13 '16 at 20:00
  • 1
    Sure! I won't edit the answer since it's your particular use case but here you have the code: codepaste.net/q8krbu – Luis Sanz Jun 13 '16 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.