Automatically convert WordPress content into Hashtags
Enhance your WordPress posts and pages with the Tag to Hashtag snippet, a powerful function designed to boost your site’s engagement and SEO. This snippet automatically converts words in your content that match existing WordPress tags into dynamic hashtags, seamlessly integrating them into your posts and pages without altering the original content. Each hashtag is transformed into a clickable link that directs users to the relevant tag archive pages, making it easier for visitors to explore related content and improving the overall user experience.
Features
- Automatically detects words in post and page content that match existing WordPress tags.
- Converts matching words into hashtags at runtime, adding the # symbol without modifying the original content.
- Transforms hashtags into clickable links, leading to the respective tag archive pages.
- Enhances user engagement by enabling easy navigation through related topics.
- Improves SEO by creating additional internal links within your site.
- Compatible with both Classic and Block editors, ensuring smooth integration with your content creation workflow.
- Lightweight and efficient, ensuring minimal impact on site performance.
Benefits
- Increased User Engagement: Keep your visitors on your site longer by providing easy access to related content.
- Improved SEO: Enhance your internal linking structure, helping search engines better understand and index your content.
- Seamless Integration: Works effortlessly with your existing tags and content, requiring no manual intervention.
- User-Friendly Navigation: Make it simple for users to discover and explore more of your content.
How It Works
Debugging
Instructions:
Add this snippet to the functions.php file of your active theme.
class TagToHashtag {
public function __construct() {
add_filter('the_content', [$this, 'makeTagsHashtags']);
}
/**
* Converts matching words in post content to clickable hashtags.
*
* @param string $content
* @return string
*/
public function makeTagsHashtags(string $content): string {
$siteurl = esc_url(get_site_url());
// Get all tags dynamically each time to ensure they are up-to-date
$tags = get_terms('post_tag', ['fields' => 'names', 'hide_empty' => false]);
// Debug: Log the tags
error_log('Tags: ' . print_r($tags, true));
foreach ($tags as $tag) {
$escaped_tag = preg_quote($tag, '/');
// Match whole words, ignore punctuation and HTML entities
$content = preg_replace_callback(
'/(?<!\w)(' . $escaped_tag . ')(?!\w)/i',
function ($matches) use ($siteurl, $tag) {
return '<a class="hashtags" href="' . esc_url(get_term_link($tag, 'post_tag')) . '" target="_blank" rel="noopener">#' . esc_html($tag) . '</a>';
},
$content
);
}
// Debug: Log the processed content
error_log('Processed content: ' . $content);
return $content;
}
}
new TagToHashtag();