Linking to Internal Posts

One of the most fustrating things for WordPress content managers is linking to other posts or pages within the system. It usually involves opening another window to the site, browsing to the required post or page, copying the URL and pasting it into the page. A simple plug-in using the relatively new shortcode system can make life a lot easier.

I’ve developed a super simple plug-in to solve the problem and demonstrate shortcode creation. Here is the functional code for the plug-in:

function pl_do_post_link($atts, $content = null) {
  //create a link to the post or page of id=xxx, or the category of cat=xxx or catname=xxxxxxxx
  global $wpdb;
  $op = $content;

  if ($content) :
    if (isset($atts['id'])) {
      $pid = $atts['id'];
      $qry = "SELECT post_title, post_type from $wpdb->posts WHERE ID=$pid";
      $p = $wpdb->get_row($qry);
      if ($p) {
      if ($p->post_type == 'page') {
        $op = '<a href="'.get_page_link($pid).'" title="'.$p->post_title.'">'.
$content.'</a>';
      } else {
        $op = '<a href="'.get_permalink($pid).'" title="'.$p->post_title.'">'.
$content.'</a>';
          }
      }
     } else {
        $catid = (isset($atts['catname'])) ? get_cat_ID($atts['catname']) : $atts['cat'];
        if  ($catid) {
           $c = get_category($catid);
           if ($c) $op = '<a href="'.get_category_link($c->cat_ID).'" title="'.
$c->cat_name.' posts">'.$content.'</a>';
       }
     }
 endif;
 return $op;
}
add_shortcode('link', 'pl_do_post_link');

As you can see, it also allows for links to categories either by ID or name. Here’s an example of the use of this shortcode: [link id=245]A Link[/link] which results in A Link and [link catname=wordpress]Another Link[/link] Another Link.

The ID passed in the “link” shortcode is the ID of the required post or page which can be determined from the post/page list screen. A future improvement would be to list all the available posts/pages within the editor, but this plug-in is a set in the right direction.

Note that this code returns the content between the [link]...[/link] tags by default to ensure that if invalid parameters are passed in the shortcode, something is still displayed on the page, though it won’t be a link. This serves as a prompt to the user. A more direct, though intrusive, alternative is to return a message such as INVALID LINK. Either way, shortcode handlers should always return SOMETHING.

Download postlink.zip

This entry was posted in Plug-in, Wordpress and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>