Guest Author – How to modify my custom function code if the guest author URL will follow a particular pattern/format?

Now I’ve understand the question, and yes, it makes sense.

The filter additions and the third function do not change at all, what change are the first two functions.

There is 2 cases:

  1. [AuthorName] part in the url is equivalent sanitize_title($guestauthor) where $guestauthor is what is saved in the ‘guest-author’ custom field
  2. [AuthorName] part is different and indipendent from ‘guest-author’ custom field

In 1st case we can assume guest authors have always a custom url and you don’t need the ‘guest-url’ custom field at all. The code become:

function guest_author_url($url) {
  global $post;
  $guest_url_suffix = sanitize_title( get_post_meta( $post->ID, 'guest-author', true ) );
  $guest_url = $guest_url_suffix ? site_url() . '/author/' .  $guest_url_suffix : null;
  if ( filter_var($guest_url, FILTER_VALIDATE_URL) ) {
    return $guest_url;
  }
  return $url;
}

function guest_author_link($name) {
  global $post;
  $guest_name = get_post_meta( $post->ID, 'guest-author', true );
  $guest_url = $guest_name ? site_url() . '/author/' . sanitize_title($guest_name) : null;
  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>';
  }
  return $name;
}

In 2nd case, in the ‘guest_url’ custom field you have to put the [AuthorName] part of the url. This give you a bonus possibility: if you don’t put anything in this field no link will ever shown for the user. The code for this case is:

function guest_author_url($url) {
  global $post;
  $guest_url_suffix = get_post_meta( $post->ID, 'guest-url', true );
  $guest_url = $guest_url_suffix ? site_url() . '/author/' .  $guest_url_suffix : null;
  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_suffix = get_post_meta( $post->ID, 'guest-url', true );
  $guest_url = $guest_url_suffix ? site_url() . '/author/' .  $guest_url_suffix : null;
  $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;
}

New code is untested, but – unless any typo – it should work.

Leave a Comment