Skip to content

Instantly share code, notes, and snippets.

@mrwweb
Created June 12, 2013 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrwweb/5770024 to your computer and use it in GitHub Desktop.
Save mrwweb/5770024 to your computer and use it in GitHub Desktop.
A function to output a delimited list of posts given an array of IDs in WordPress
<?php
/**
* Make a list of links to WordPress posts
*
* Works great with the Relationship field from Advanced Custom Fields
*
* @param array $posts array of post objects or post_ids
* @param string $sep separater
* @param string $before output before the list
* @param string $after output after the list
* @param bool $links whether to link titles to posts, default = true
* @param 'objects'|'ids' $type whether the $posts param contains objects or IDs. Default: 'objects'
* @return string links separated by commas
*/
function ciswa_posts_list( $posts, $sep = ', ', $before = '', $after = '', $links = true, $type = 'objects' ) {
if( ! $posts && ! is_array( $posts ) )
return; // nothing to do
if( $type = 'objects' ) {
$posts = wp_list_pluck( $posts, 'ID' );
}
$post_links = array();
if( (bool) $links ) {
foreach ($posts as $key => $id) {
$post_links[] = '<a href="' . esc_url( get_permalink( $id ) ) . '">' . esc_attr( get_the_title( $id ) ) . '</a>';
}
} else {
foreach ($posts as $key => $id) {
$post_links[] = esc_attr( get_the_title( $id ) );
}
}
return $before . implode( $sep, $post_links ) . $after;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment