WordPress: Get Page Title by ID

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

<?php getPageTitle(ID); ?>
function getPageTitle($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->post_title);
		}
	}
}

One Response to WordPress: Get Page Title by ID

  1. Why not “<?php echo get_the_title($pageId) ?>” ?
    Cheers

Leave a Reply