How should I add links to other pages/posts from my post?

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?

Related posts

1 comment

  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.

Comments are closed.