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
    If comma is used to separate then you can use explode function to get each meta value. – Nilambar Mar 19 '15 at 3:17

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 ;-)

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.