[EXTENSION] Autolink posts/pages with keywords

Post Reply
User avatar
VanHalen
Jr. Bludit
Posts: 9
Joined: Wed Jun 29, 2016 2:48 pm
Location: The Netherlands

I needed a 'auto link' feature for a client to link specific keywords in posts and pages to the corresponding posts and pages with the same post/page title. Maybe someone else has some use for it:

1. Activate the Bludit API plugin, go to settings and copy your API urls.

2. Modify your theme's page.php and/or post.php

Code: Select all

$Post->Content;
with

Code: Select all

keywords($Post->Content());

Code: Select all

$Page->Content;
with

Code: Select all

keywords($Page->Content());
3. Include the function below in your theme's head.php or in a file like functions.php

Code: Select all

function keywords($content) {

	global $Page, $Post;
	
	// Get all published Post & Pages
	
	$pagesURL = 'http://yourdomain.tld/api/show/all/pages/yourapikey';
	$pageJSON = file_get_contents($pagesURL);
	$pageData = json_decode($pageJSON, true);

	$postsURL = 'http://yourdomain.tld/api/show/all/posts/yourapikey';
	$postJSON = file_get_contents($postsURL);
	$postData = json_decode($postJSON, true);

	$PostPages = array_merge_recursive($postData,$pageData);

	if($Post) $title = $Post->title();
	if($Page) $title = $Page->title();
	
	foreach($PostPages as $PostPage):

		if($PostPage['title'] != $title):
			$keywords[$PostPage['title']] = $PostPage['permalink'];
		endif;

	endforeach;

	// Match all words with Pages and Post titles (modified):
	// http://stackoverflow.com/questions/3905764/howto-change-some-words-into-links-in-html/3907091#3907091
	
	$wordExpressions = array();
	$wordReplacements = array();

	foreach($keywords as $cWord => $cLink):
		$wordExpressions[] = '#<strong>' . preg_quote($cWord) . '#';
		$wordReplacements[] = '<false href="' . $cLink . '"><strong>' . $cWord . '</false>';
	endforeach;

	$newContent = preg_replace($wordExpressions,$wordReplacements,$content);
	$newContent = preg_replace_callback("#(<a [^>]*>)((?:[^<]|<(?!/?a>)|(?R))+)(</a>)#", create_function('$a', 'return $a[1] . preg_replace("#<false[^>]*>(.*?)</false>#", "$1", $a[2]) . $a[3];'), $newContent);
	$newContent = preg_replace(array('#<false #','#</false>#'),array('<a ','</a>'),$newContent);

	return $newContent;
	
}
The function above is case-sensitive so both the keyword in the content and the post/page title needs to be exactly the same and that it only works with keywords enclosed with a <strong> tag.

Example:
<strong>Home</strong> will create a link to your Home page inside any post/page content.

Feel free to modify it to suit your needs.
Post Reply