Multiple meta values for one meta key

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.

Topic user-meta Wordpress

Category Web


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>';
}

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.