Last Updated on April 3, 2020 by Neil Murray
This site uses many internal links to relate to other pages. It is very easy to create a post/page link to other page using WordPress editor, but once we modify the page slug, move the page to other hierarchy, or move the site completely with different domain, we will got 404 not found page.
For a workaround for this issue, we should avoid static link to a post or page, and use a shortcode that generates the link automatically based on post ID. We can find the ID of post or page in respected admin edit screen as screenshot above from https://team.cf7skins.com/wp-admin/edit.php?post_type=page for Page type.

Creating Shortcode Link
Creating a shortcode in WordPress is easy, we just need to register our shortcode function using add_shortcode and shortcode_atts to combind user shortcode attributes with default shortcode attributes.
Here is how the code looks like:
function cf7skins_link( $atts ) {
$atts = shortcode_atts( array(
'id' => 701,
'text' => '',
), $atts, 'link' );
extract( $atts, EXTR_SKIP ); // extract attributes
if ( $permalink = get_permalink( $id ) ) { // return string if found or false.
$title = $text ? $text : get_the_title( $id );
return "<a href='$permalink'>$title</a>";
} else {
return 'Error, the post or page does not exist!';
}
}
add_shortcode( 'link', 'cf7skins_link' );
The shortcode takes two attributes or parameters, id for the post ID and title for custom post/page title. If title is not set, than it will use the post title itself. The function will finds the post ID, create the link if found, or display error message if not exist.
To use the shortcode, simply add a square bracket with link string, provide the post ID and custom title if needed.
[link id="144"]
That’s it, with a few lines, we can add post/page link automatically, and save the site from 404 suffering.
