Automatic Internal Links for Keywords
Turns the first mention of chosen keywords in each post into a link to the page you pick, building internal links without editing every post.
Opens WPIDE on
Code
// Keyword => URL (full URL or a path on this site). Examples:
// 'contact us' => '/contact/',
// 'our services' => '/services/',
$wpide_keyword_links = array();
add_filter( 'the_content', function ( $content ) use ( $wpide_keyword_links ) {
if ( ! $wpide_keyword_links || ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$current = untrailingslashit( (string) get_permalink() );
$parts = preg_split( '/(<[^>]+>)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
$depth = 0;
$done = array();
$tokens = array();
foreach ( $parts as $i => $part ) {
if ( '' === $part ) {
continue;
}
if ( '<' === $part[0] ) {
if ( preg_match( '/^<(a|h[1-6]|code|pre|script|style|button|textarea)[\s>]/i', $part ) ) {
$depth++;
} elseif ( preg_match( '/^<\/(a|h[1-6]|code|pre|script|style|button|textarea)>/i', $part ) ) {
$depth = max( 0, $depth - 1 );
}
continue;
}
if ( $depth ) {
continue;
}
foreach ( $wpide_keyword_links as $keyword => $url ) {
if ( isset( $done[ $keyword ] ) ) {
continue;
}
$href = preg_match( '#^https?://#', $url ) ? $url : home_url( $url );
if ( untrailingslashit( $href ) === $current ) {
$done[ $keyword ] = true;
continue;
}
$new = preg_replace_callback( '/\b(' . preg_quote( $keyword, '/' ) . ')\b/iu', function ( $m ) use ( $href, &$tokens ) {
$tokens[] = '<a class="wpide-auto-link" href="' . esc_url( $href ) . '">' . $m[1] . '</a>';
return "\x01" . ( count( $tokens ) - 1 ) . "\x02";
}, $part, 1, $count );
if ( $count && null !== $new ) {
$parts[ $i ] = $new;
$part = $new;
$done[ $keyword ] = true;
}
}
}
$content = implode( '', $parts );
foreach ( $tokens as $index => $link ) {
$content = str_replace( "\x01" . $index . "\x02", $link, $content );
}
return $content;
}, 20 );
Notes
Add your keywords and target pages to the list first; it is empty by default. Links are not added inside headings, existing links, code or buttons, and a post 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.