0

I have a custom field type set up and need a way for a client to add a list of links that I can then output as a UL with each being an LI. I am hoping they can enter a comma separated list in the input and I can output the list with php where each value in between the commas can be separated out.enter image description here

or maybe it can be done if they put each link on a new line? Or maybe there is a better way to tackle this, it's my first attempt at using/creating custom post types.

  • 1
    Using a custom field plugin, you could more easily define the type of content they can enter into each box. ACF has a nice "repeater" field type that will let you add as few or as many items as you need, and an "url" field type that requires them to enter a URL. This would ensure they enter properly formatted links and prevent issues with commas, semicolons, etc. if you have a somewhat less tech-savvy user or just someone who is prone to typos. – WebElaine Nov 13 '17 at 16:05
  • Are those options on the premium version of ACF? I'm using the free one. – jessica mele Nov 13 '17 at 16:25
  • Yes, repeater is premium. Not sure on URL. – WebElaine Nov 13 '17 at 16:49
0

If I understood you correctly, this should be pretty straight forward:

$rawcontent = get_field("myfield");
$rawcontent = preg_replace("!</?p[^>]*>!", "", $rawcontent); // remove <p>
$all_links = preg_split("/\s*,\s*/", $rawcontent);
foreach($all_links as $link) {
    if(!trim($link)) continue;
    print "<li>$link</li>";
}

A comma certainly would work, but note that this would break if you had commas inside the link text (<a href="...">hello, world</a>). You could easily alter the preg_split line to split on other things, though, like line breaks (\n). I'm not sure what the ACF editor inserts when you just press enter, but I'm sure that you can split it.

  • That created a <li></li> but it's empty – jessica mele Nov 13 '17 at 16:34
  • That's why you should run the code you post here ;) Sorry, I had a typo, $rawcontent vs $raw_content. See the edited version, or fix it in your code. – janh Nov 13 '17 at 16:35
  • @janh is that correct for new lines? /\n*,\n*/ – techno Nov 13 '17 at 16:56
  • <?php $rawcontent = get_field('resources'); $all_links = preg_split("/(\n)/", $rawcontent); foreach($all_links as $link) { print "<li><a href='$link'></a></li>"; } ?> – jessica mele Nov 13 '17 at 17:03
  • I used $all_links = preg_split("/(\n)/", $rawcontent); with a new line start and that seemed to do the trick. The problem I'm facing now is because I am adding them in a wysiwyg editor it is wrapping each entry in a <p> tag so my output is showing up like <li><a href="<p>www.mylink1.com</p>"><a/> and there is a blank <li> at the end. – jessica mele Nov 13 '17 at 17:12

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.