1

I'm wondering how should I link to other posts from one of my posts. Ideally I would use a function like get_permalink() but php is not available in post content, so how can I link to other pages ensuring the links won't break if I change the post/pages slugs?

1 Answer 1

1

You have a couple options. Both involve using the post ID because that doesn't change.

  1. You could use the ugly URL in the form of http://www.example.com/?p=23 where ?p=23 would be the ID of the post.

  2. You can use a shortcode that accepts the post ID and outputs a link using get_permalink().

The following shortcode would be used like this.

[postlink id=23]Some link text goes here[/postlink]

And here is the function.

function postlink_id_to_slug( $atts, $content = null ) {
extract( shortcode_atts( array(
    'id' => ''
), $atts ) );

if ( $id == '' || ! is_numeric( $id ) || $content == null) return false;

return '<a href="' . get_permalink( $id ) . '">' . $content . '</a>';
}
add_shortcode( 'postlink', 'postlink_id_to_slug' );

I should mention that there are a number of ways to find the ID of a post. One way is to open the post in the post editor and then find post=xx in the URL in your browser's address field where xx is the numerical ID.


Just to know: this plugin does same thing in a more flexible manner.

2
  • @G.M. You should offer that up as an answer so people will see it.
    – epilektric
    Aug 30, 2013 at 23:20
  • Just edited your answer. All the honors to you ;)
    – gmazzap
    Aug 30, 2013 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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