Creating clickable links within WordPress post excerpts can significantly enhance user experience, making it easier for readers to navigate to the intended URLs. If you'd like to transform plain text links in excerpts into clickable links, you can use the following PHP code. This code snippet can be added to your functions.php
file or, preferably, packaged into a plugin using our WordPress Plugin Generator.
The Solution
Below is the very efficient code that checks if there are any (text) links in the excerpt and then replaces each text link with a clickable one. It also works on the public side only so you as admin can enter text links and don't have to edit HTML code in the admin. You just need to type e.g. https://wpsandbox.net and it will be converted into an HTML link that opens in a new tab.
If you want you may also add rel="nofollow" attribute to not affect your site's SEO. Check with SEO professionals though.
<?php
/**
* Plugin Name: WPSandbox Tutorial: #1221 - Clickable Post Excerpt Links
* Plugin URI: https://wpsandbox.net/post1221
* Description: Converts all text links from the post excerpt into clickable links (public side only) based on WPSandbox post - https://wpsandbox.net/1221
* Author: Svetoslav Marinov (Slavi) | WPSandbox
* Author URI: https://wpsandbox.net
* Version: 1.0.0
* Text Domain: wpsandbox_1221
* Requires at least: 3.7
* Requires PHP: 5.6
*/
function wpsandbox1221_clickable_excerpts( $excerpt, $post_obj = null ) {
// does it have a link? This will save us checking for http:// or https://, smart, eh?
if (empty($excerpt) || (strpos($excerpt, '://') === false)) {
return $excerpt;
}
// is this admin area? if so don't modify the content there. Update it only on the public side only.
if (is_admin()) {
return $excerpt;
}
$regex = '/\b(https?:\/\/[^\s<]+)(?![^<>]*>)/is';
// Use preg_replace_callback to replace each match with a clickable link
$excerpt = preg_replace_callback($regex, function($matches) {
$url = esc_url($matches[0]);
return sprintf('<a href="%s" target="_blank">%s</a>', $url, $url);
}, $excerpt);
return $excerpt;
}
add_filter( 'get_the_excerpt', 'wpsandbox1221_clickable_excerpts', 25, 2 );