1

I have one meta key "game" containing this meta value "game 1, game 2".

I would like to display this meta value on my site like this:

<a href="http://www.url.com/game-1">game 1</a>
<a href="http://www.url.com/game-2">game 2</a>

Thanks for your help.

1
  • 1
    If comma is used to separate then you can use explode function to get each meta value. Commented Mar 19, 2015 at 3:17

2 Answers 2

0

If multiple entries are stored in a single meta key, then get_post_meta() will return an array of those values.

get_post_meta( $post_id, 'game' ); // returns ['game 1', 'game 2']

If you want to iterate through the collection, then you'll just use a for-loop in PHP:

$games = get_post_meta( $post_id, 'game' );
foreach( $games as $game ) {
    $game_slug = sanitize_title( $game ); // Turns "game 1" into "game-1" for URL usage
    $game_url = 'http://www.url.com/' . $game_slug;

    echo '<a href="' . esc_url( $game_url ) . "'>' . esc_html( $game ) . '</a>';
}

I've added escaping above for both the URL and the title so the rendered markup will be as safe as possible - we don't want anyone embedding a script tag as a game title and hijacking the site ;-)

1
  • High five for sanitation and escaping! This should be standard practice but unfortunately isn't always
    – sMyles
    Commented Mar 4, 2021 at 0:16
0

If the meta is saved in CSV format (and single meta), using the same output handling as @EAMann, this is how you would do it for a single value meta field:

$games = get_post_meta( $post_id, 'game', true );
$games = explode(',', $games );
foreach( $games as $game ) {
    $game_slug = sanitize_title( $game ); // Turns "game 1" into "game-1" for URL usage
    $game_url = 'http://www.url.com/' . $game_slug;

    echo '<a href="' . esc_url( $game_url ) . "'>' . esc_html( $game ) . '</a>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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