Custom WordPress Functions – Hyperlink Title

Custom WordPress Functions: Hyperlink a Page or Post Title

Custom WordPress plugin and theme development often requires the writing of custom WordPress functions. linkify_title is a simple PHP function that uses 2 built-in WordPress functions get_page_by_title and get_permalink. The purpose of linkify_title is to convert a title string into hyperlinked text. It can be used by incorporating into the functions.php file in your WordPress directory. If developing a custom plugin, it can also be included in one of your plugin files.

Brief instructions follow. NOTE: If including this in function.php file, do so via a child theme in order to avoid losing it in subsequent theme or WordPress updates.

Linkify Function Code

/**
 * 
 * Custom PHP function to convert WP page or post title into hyperlinked text.
 * Function checks for title in both page and post types. Default type is post.
 * If the page/post url is not found, function returns title text only. 
 * If the page/post url IS found, function returns title wrapped in hyperlink tags.
 * 
 * @param string $title
 * @return string
 */
public function linkify_title( $title ) {
	$url = '';
	if ( $pageObj = get_page_by_title( $page_title = $title, $output = OBJECT, $post_type = 'post' ) ) {
		$url = get_permalink( $pageObj );
	} elseif ( $pageObj = get_page_by_title( $page_title = $title, $output = OBJECT, $post_type = 'page' ) ) {
		$url = get_permalink( $pageObj );
	}
	if ( !empty( $url ) ) {
		return '<a href="' . $url . '">' . $title . '</a>';
	} else {
		return $title;
	}
}

Example usage:

// retrieve page title by ID or just use a known title string
$page_title = get_the_title( $ID = $post_id );
// get the linked title
$linked_title = linkify_title( $page_title );
// output the linked title
echo "<p>The page title = $page_title</p>";
echo "<p>The linked title = $linked_title</p>";

This is a simple PHP function that can be used within or outside the loop. Generally we embed utility-type WordPress functions in an abstract PHP utilities class. The PHP utilities class is loaded during theme or plugin setup so that it can be used as needed by other classes and functions.