Learning never exhausts the mind

By

We all know that it is good to have links posts and categories throughout your site, but maintaining hard coded links can be a pain, especially when things like permalink structure or domain name change. These two functions will allow you to create flexible dynamic links in your posts or pages.

So you have a blog with hundreds of posts each of them interlinked. Then you decide to change your domain name, permalink structure or something else and you have to update all the posts again. Why not update them with a dynamic link and let WordPress generate the URL for you?

You will need RunPHP or similar for these to work inside posts and pages, but they are not needed is you use them in templates.

The first function will create a link to a post. You must specify a post id to link to, you can optionally specify a title for the link (the text to show) and you can return the link as a string variable instead of printing on the page. If no title is passed in then the post/page title will be used instead. These functions should be placed within functions.php in you themes folder.

function linkToPost($postid, $linkTitle = "", $echo = true)
{
  $linkurl = get_permalink($postid);
  
  if ($linkTitle == "")
    $linkTitle = get_the_title($postid);
    
  $link = '<a href="' . $linkurl . '" >' . $linkTitle . '</a>';
  
  if ($echo === true) 
    echo $link; 
  else 
    return $link;
}

The second function works in the same was as the first, however it will link to categories instead.

function linkToCat($catID, $linkTitle = "")
{
  $cat = get_category_link($catID);
  $link = '<a href="' . $cat . '" >' . $linkTitle . '</a>';
  echo $link;
}

Usage

Lets say you are writing a post and want to link to another post with an ID of 53 (ID numbers can be found when viewing/editing posts in the wordpress admin screens). To create a simple link to post 53 use the following:

<?php LinkToPost(53); ?>

This will be executed by RunPHP so that when the post is viewed you will have a nice link which will always be correct.

To change the title to something other than the post title use the functions like this:

<?php LinkToPost(53,"this is my new title"); ?>

And you can capture the output into a variable like this:

<?php $cleanLink = LinkToPost(53,"this is my title", false); ?>

 

Enjoyed this post? Why not share it!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.