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

  • Automatic Detection: The snippet scans your content for words that match your existing WordPress tags whenever a post or page is saved.
  • Dynamic Hashtags: At runtime, these matching words are dynamically converted into hashtags and linked to their respective tag archive pages.
  • Preserved Original Content: Your original content remains unaltered, with hashtags added only during front-end rendering.
  • 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();

    Comments

    1. I tried to use it, it created the hashtag but when click on it , it shows 404 error

      1. Hi Jola, thank you for pointing it out 👍
        The code has been updated and tested today to work with WordPress Version 6.6.1 and PHP 8.3.
        Please feel free to add comments if you experience any bugs or have suggestions for further functionality.

        Have a great one – WPDYN 🤘

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Contact Us

    This could be the beginning of something great 🙌

    "*" indicates required fields

    Name*
    Hidden
    Hidden

    By submitting this form: You agree to the processing of the submitted data in accordance with WP Dynamics Privacy Policy.

    Contact Information
    You can also write us an email or contact us by telephone.
    Telephone +45 71 74 71 21

    Support For support inquiries, please refer to our support section.

    Recent Articles

    Faust.js – A Headless Framework for WordPress

    Faust.js is a Headless WordPress Framework that provides a set of tools for building front-end applications based on WordPress ...

    How to Load (Enqueue) and Handle Assets and Dependencies in WordPress

    In WordPress, instead of adding assets such as styles and JavaScript to the header, you can and should use ...

    An Introduction to Google Tag Manager Server-side Tagging

    WordPress has come a long way since its launch in 2003 - from a blogging tool to a full-fledge ...