0

I have this permalink structure: /%year%/%monthnum%/%postname%/

What I want to is, output the link of a post in the back-end and let users input a postname, that will automatically lead to that post (if it exists, otherwise 404)...

So, I have this:

function transform_pseudo_anchor_wpse_101201($match) {
  if (isset($match[1])) {
    return '(link: <a href="http://example.com/'.sanitize_title_with_dashes($match[1]).'" title="'.$match[1].'">'.$match[1].'</a>)';
  }
}

$content = preg_replace_callback(
  '%\(link: ?(.*?) ?\)%', 
  'transform_pseudo_anchor_wpse_101201', 
  $content
); 
echo $content; 

Of course, this does not work... But how can I make it work? So I want the get the exact link if someone links to a post that exists... So after example.com, the year/monthnum and postname has to come...

0

Your code works to create links, and WordPress should make a valiant effort to find the correct post, but it doesn't get complete permalinks. To do that you will need to query the database for the post and construct a permalink if one is found.

function transform_pseudo_anchor_wpse_101201($match) {
  global $wpdb;
  if (isset($match[1])) {
    $name = sanitize_title_with_dashes($match[1]);
    $p = new WP_Query(
      array(
        'name'=>$name,
        'post_type' => 'post',
        'posts_per_page' => 1,
        'suppress_filters' => true,
        'ignore_sticky_posts' => true
      )
    );
    if (!empty($p->posts[0])) {
      $link = get_permalink($p->posts[0]);
      return '(link: <a href="'.$link.'" title="'.$match[1].'">'.$match[1].'</a>)';
    } else {
      return 'nada';
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.