WordPress: get page link by ID

This function is used to get the_permalink() of a certain page using it’s ID (outside the loop). To use it within a theme, just:

<?php getPageLink(ID); ?>
function getPageLink($pageId){
   if(!is_numeric($pageId)) {
      return;
   }
   global $wpdb;
   $sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts . ' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
   $posts = $wpdb->get_results($sql_query);
   if(!empty($posts)) {
      foreach($posts as $post) {
         return nl2br($post->guid);
      }
   }
}

Leave a Reply