<?php
if (!defined('ABSPATH')) exit;

class SS_AutoLinker {

    public function __construct() {
        add_filter('the_content', [$this, 'auto_link_terms'], 20);
    }

    public function auto_link_terms($content) {

        if (is_admin()) {
            return $content;
        }

        $terms = get_posts([
            'post_type'      => 'ss_glossary',
            'posts_per_page' => -1,
            'post_status'    => 'publish'
        ]);

        if (!$terms) {
            return $content;
        }

        foreach ($terms as $term) {

            $term_name = $term->post_title;
            $term_url  = get_permalink($term->ID);

            $pattern = '/\b' . preg_quote($term_name, '/') . '\b/i';

            $replacement = '<a class="ss-glossary-term" href="' . esc_url($term_url) . '">' . esc_html($term_name) . '</a>';

            $content = preg_replace($pattern, $replacement, $content, 1);
        }

        return $content;
    }
}

new SS_AutoLinker();