This isn’t really a WordPress question, but since you’re using the Loop, a lot of people will assume it’s WordPress-specific. That being said, the solution is to use PHP’s native array-to-string conversion utilities.
Instead of the code you do have, you’ll want to use something like:
<?php
$posts = get_field( 'author_name' );
if ( $posts ) {
echo ' <img src="https://wordpress.stackexchange.com/questions/199446/aut.png" alt="authors" height="20" width="20"> ';
$post_list = array();
foreach ( $posts as $post ) { // variable must be called $post (IMPORTANT)
setup_postdata( $post );
$post_list[] = sprintf( '<a href="%s">%s</a>', esc_url( get_the_permalink() ), esc_html( get_the_title() ) );
}
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
echo implode( ', ', $post_list );
}
Very briefly, this updates your original code to do a few things:
- It uses the
HTML entity instead of attempting to concatenate a strings with extra spaces (more performant) - It builds up an array of post entries and uses PHP’s native
implode()
to join the entries together with commas. - It uses
sprintf()
to make the post entry generation a bit cleaner - It uses proper escaping for the permalink and the post title to prevent stored XSS vulnerabilities
Again, these changes are vanilla PHP, we just happen to be using a WordPress loop and WordPress template tags.