Guest Author – How can I use custom fields to create guest author link?

Remove the filters and the function used in the tutorial you linked and replace them with this code:

add_filter( 'get_the_author_user_url', 'guest_author_url' ); 
add_filter( 'the_author', 'guest_author_link' ); 
add_filter( 'get_the_author_display_name', 'guest_author_name' );

function guest_author_url($url) {
  global $post;
  $guest_url = get_post_meta( $post->ID, 'guest-url', true );
  if ( filter_var($guest_url, FILTER_VALIDATE_URL) ) {
    return $guest_url;
  } elseif ( get_post_meta( $post->ID, 'guest-author', true ) ) {
    return '#';
  }
  return $url;
}

function guest_author_link($name) {
  global $post;
  $guest_url = get_post_meta( $post->ID, 'guest-url', true );
  $guest_name = get_post_meta( $post->ID, 'guest-author', true );
  if ( $guest_name && filter_var($guest_url, FILTER_VALIDATE_URL) ) {
    return '<a href="' . esc_url( $guest_url ) . '" title="' . esc_attr( sprintf(__("Visit %s&#8217;s website"), $guest_name) ) . '" rel="author external">' . $guest_name . '</a>';
  } elseif( $guest_name ) {
    return $guest_name;
  }
  return $name;
}

function guest_author_name( $name ) {
  global $post;
  $guest_name = get_post_meta( $post->ID, 'guest-author', true );
  if ( $guest_name ) return $guest_name;
  return $name;
}

Now you can use the_author_link() to see name and link for your guest author, but note that if your guest author has not a url the functions will show the name of the guest author linking the same page (href="#").

If you don’t like this behavior, in your template file replace the_author_link() with the_author() and if your guest author has a name and a url the link is shown, otherwise you will see only the name.

Note that guest url must be a valid url (start with http:// or https://) or it will not be shown.

Leave a Comment

tech