Skip to Content
Frontlane Studio
All Snippets
PHP WordPress November 14, 2024

Auto-Link Keywords in Post Content Using make_clickable

A PHP snippet for Auto-Link Keywords in Post Content Using make_clickable.

WordPress PHP

A PHP snippet for Auto-Link Keywords in Post Content Using make_clickable.

function auto_link_keywords($content) {
    // Define keywords and their respective URLs.
    $keywords = array(
        'WordPress' => 'https://wordpress.org/',
        'WooCommerce' => 'https://woocommerce.com/',
        'Gutenberg' => 'https://wordpress.org/gutenberg/',
    );

    // Loop through each keyword and wrap it in a clickable link.
    foreach ($keywords as $keyword => $url) {
        $content = preg_replace(
            '/\b' . preg_quote($keyword, '/') . '\b/i',
            '<a href="' . esc_url($url) . '" target="_blank">' . $keyword . '</a>',
            $content
        );
    }

    return make_clickable($content);
}

add_filter('the_content', 'auto_link_keywords');