Rajiv Srivastava
Rajiv Srivastava

Reputation: 25

Explode comma separated values to append anchor href for each value

Comma seprated values are stored in a wordpress field. Now I want to echo out all the comma seprated values into anchors <a href="value1">value1</a> <br> <a href="value2">value2</a> etc. Number of comma seprate values shold be same a appended anchors. (It should not show any space in next value, if there is space after comma)

I have tried it by using,

$values = explode(',', ''. get_post_meta( $order->id, '_xrd_ref', true ) .'');
foreach ($values) {echo '<p><a href="https://example.com/'. $values .'">'. __( '. $values .' ) . '</a><p>';}

Upvotes: 1

Views: 36

Answers (1)

Ken Lee
Ken Lee

Reputation: 8063

You need a loop (typically a foreach) to display the array of strings returned by explode().

So

$bvalues = explode(',', ''. get_post_meta( $order->id, '_xrd_ref', true ) .'');

foreach ($bvalues as $values) {

 if (trim($values) !="") {
  echo '<p><a href="https://example.com/'. str_replace('%20','',trim($values)) .'">'. str_replace('%20','',trim($values)) . '</a><p>';
 }
}

Alternatively,

$bvalues = explode(',', ''. get_post_meta( $order->id, '_xrd_ref', true ) .'');

foreach ($bvalues as $values) {

  $newstring=str_replace('%20','',trim($values));

 if (trim($newstring) !="") {
  echo '<p><a href="https://example.com/'. $newstring .'">'. $newstring . '</a><p>';
 }
}

Amend the code if necessary to suit your needs.

Upvotes: 2

Related Questions