Curently if we use the insert link dialog to insert a link to another post, WordPress always use the permalink of that post. The problem is when we change permalink structure, that link will be broken.

I'd like to ask if there is a way to change the link from permalink to shortlink like ?p=123 to make it work in any circumstance.


  • Technically interesting, but I would argue it makes more sense to invest in backwards compatibility when configuration is changed rather than avoid using permalinks. :)
    – Rarst
    Sep 16, 2012 at 16:23
  • Yes, maybe somehow change all links in post content to shortlink?
    – Anh Tran
    Sep 16, 2012 at 16:31
  • 1
    What if someone links to the site elsewhere? No control over there. Old links should be just redirected to new ones if the settings change (via htaccess or WP code either).
    – Rarst
    Sep 16, 2012 at 16:39

1 Answer 1


The links in that dialog are made by wp_ajax_wp_link_ajax() (see wp-admin/includes/ajax-actions.php, there is no page on Codex or queryposts.com for that function).

To change the links filter 'page_link', 'post_type_link', 'post_link' and maybe 'attachment_link' after check_ajax_referer() was called for the action 'internal-linking'.

Okay, sounds a little bit complicated, but it is really easy. :)
Plugin on GitHub: https://gist.github.com/3731739

add_action( 'check_ajax_referer', 't5_temporary_internal_links', 10, 1 );

 * Turn permalinks into dynamic links.
 * @param   string $action_or_link Action when called per 'check_ajax_referer',
 *                                later the permalink.
 * @param   object|integer $post
 * @wp-hook check_ajax_referer
 * @wp-hook page_link
 * @wp-hook attachment_link
 * @wp-hook post_type_link
 * @wp-hook post_link
 * @since   2012.09.16
 * @return  string
function t5_temporary_internal_links( $action_or_link, $post = 0 )
    if ( 'check_ajax_referer' === current_filter()
        and 'internal-linking' === $action_or_link
        add_filter( 'page_link',       __FUNCTION__, 10, 2 );
        // You cannot search for attachments in this dialog,
        // but a plugin might have changed that, so …
        add_filter( 'attachment_link', __FUNCTION__, 10, 2 );
        add_filter( 'post_type_link',  __FUNCTION__, 10, 2 );
        add_filter( 'post_link',       __FUNCTION__, 10, 2 );

    $id = is_object( $post ) ? $post->ID : $post;
    return home_url( "?p=$id" );

But … when you change permalinks you have to create redirects in a server configuration file anyway to redirect existing URLs. So I am not sure if this plugin is really needed.

  • 1
    Very nice code! Works like a charm! I like the way you use one function for all those hooks, so tricky but cool!
    – Anh Tran
    Sep 16, 2012 at 16:13

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.