Automatic Internal Links for Key Phrases
Links the first mention of phrases you choose to the matching pages in your posts, building internal links without editing old content.
Opens WPIDE on
Code
// Phrase => URL, and the maximum number of automatic links per post.
$wpide_auto_links = array(
'technical SEO' => home_url( '/services/technical-seo/' ),
'content audit' => home_url( '/guides/content-audit/' ),
'local business' => home_url( '/local-seo/' ),
);
$wpide_auto_links_max = 5;
add_filter( 'the_content', function ( $content ) use ( $wpide_auto_links, $wpide_auto_links_max ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() || ! $wpide_auto_links ) {
return $content;
}
$current = untrailingslashit( get_permalink() );
$parts = preg_split( '/(<[^>]+>)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
$skip = 0;
$used = array();
$count = 0;
foreach ( $parts as $i => $part ) {
if ( '' === $part ) {
continue;
}
if ( '<' === $part[0] ) {
// Track whether we are inside an element whose text must not be linked.
if ( preg_match( '#^<(a|h[1-6]|code|pre|button|script|style|textarea|figcaption)\b#i', $part ) ) {
$skip++;
} elseif ( preg_match( '#^</(a|h[1-6]|code|pre|button|script|style|textarea|figcaption)>#i', $part ) ) {
$skip = max( 0, $skip - 1 );
}
continue;
}
if ( $skip || $count >= $wpide_auto_links_max ) {
continue;
}
foreach ( $wpide_auto_links as $phrase => $url ) {
if ( isset( $used[ $phrase ] ) || $count >= $wpide_auto_links_max || untrailingslashit( $url ) === $current ) {
continue;
}
$pattern = '/(?<![\p{L}\p{N}])(' . preg_quote( $phrase, '/' ) . ')(?![\p{L}\p{N}])/iu';
if ( preg_match( $pattern, $part ) ) {
$part = preg_replace( $pattern, '<a href="' . esc_url( $url ) . '" class="auto-link">$1</a>', $part, 1 );
$used[ $phrase ] = true;
$count++;
}
}
$parts[ $i ] = $part;
}
return implode( '', $parts );
}, 20 );
Notes
Matching ignores case and never links inside headings, existing links, code or buttons. Each phrase is linked once per post, and a page never links to itself.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.