*/ // Exit if accessed directly if (!defined('ABSPATH')) { exit; } /** * Frontend class. */ class AJEJSMTA_Frontend { /** * Plugin settings. * * @var array */ private $settings; /** * Used heading IDs to prevent duplicates. * * @var array */ private $used_ids = array(); /** * Constructor. */ public function __construct() { $this->settings = get_option('ajejsmta_settings', array()); $this->init_hooks(); } /** * Initialize hooks. * * @return void */ private function init_hooks() { // Enqueue scripts and styles add_action('wp_enqueue_scripts', array($this, 'enqueue_assets')); // Add TOC to content add_filter('the_content', array($this, 'add_toc_to_content'), 10); // Register shortcode add_shortcode('ajejsmta_toc', array($this, 'toc_shortcode')); } /** * Enqueue frontend assets. * * @return void */ public function enqueue_assets() { // Only enqueue on singular posts/pages if (!is_singular()) { return; } // Enqueue CSS wp_enqueue_style( 'ajejsmta-frontend', AJEJSMTA_URL . 'assets/css/frontend.css', array(), AJEJSMTA_VERSION ); // Enqueue JavaScript wp_enqueue_script( 'ajejsmta-frontend', AJEJSMTA_URL . 'assets/js/frontend.js', array(), AJEJSMTA_VERSION, true ); // Localize script wp_localize_script('ajejsmta-frontend', 'ajejeySmrtTocSettings', array( 'smoothScroll' => isset($this->settings['smooth_scroll']) ? $this->settings['smooth_scroll'] : true, 'scrollOffset' => 80, // Offset for fixed headers 'backToTop' => isset($this->settings['back_to_top']) ? $this->settings['back_to_top'] : false, 'stickyMode' => isset($this->settings['sticky_mode']) ? $this->settings['sticky_mode'] : 'none', 'hideOnScroll' => isset($this->settings['hide_on_scroll']) ? $this->settings['hide_on_scroll'] : false, )); } /** * Add TOC to content. * * @param string $content Post content. * @return string Modified content. */ public function add_toc_to_content($content) { // Check if plugin is enabled if (!isset($this->settings['enabled']) || !$this->settings['enabled']) { return $content; } // Check if we're on a singular post/page if (!is_singular()) { return $content; } // Check conditional display rules if (!$this->should_display_toc()) { return $content; } // Check position setting $position = isset($this->settings['position']) ? $this->settings['position'] : 'before'; // If shortcode position, don't auto-insert if ($position === 'shortcode') { return $content; } // Generate TOC $toc = $this->generate_toc($content); // If no TOC generated, return original content if (empty($toc)) { return $content; } // Insert TOC based on position if ($position === 'before') { return $toc . $content; } else { return $content . $toc; } } /** * Generate table of contents. * * @param string $content Post content. * @return string TOC HTML or empty string. */ public function generate_toc($content) { // Extract headings $headings = $this->extract_headings($content); // Check minimum headings requirement $min_headings = isset($this->settings['min_headings']) ? (int) $this->settings['min_headings'] : 3; if (count($headings) < $min_headings) { return ''; } // Build TOC HTML $toc_html = $this->build_toc_html($headings); return $toc_html; } /** * Extract headings from content. * * @param string $content Post content. * @return array Array of headings. */ private function extract_headings($content) { // Reset used IDs for each content parse $this->used_ids = array(); $headings = array(); // Get allowed heading levels $allowed_levels = isset($this->settings['heading_levels']) ? $this->settings['heading_levels'] : array('h2', 'h3', 'h4'); // Create regex pattern for allowed headings $pattern = '/<(' . implode('|', $allowed_levels) . ')[^>]*>(.*?)<\/\1>/i'; // Find all headings if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $level = strtolower($match[1]); $text = strip_tags($match[2]); $id = $this->generate_heading_id($text); $headings[] = array( 'level' => $level, 'text' => $text, 'id' => $id, ); } } return $headings; } /** * Generate unique ID for heading. * * @param string $text Heading text. * @return string Unique ID. */ private function generate_heading_id($text) { // Remove HTML tags $text = strip_tags($text); // Convert to lowercase with UTF-8 support $id = mb_strtolower($text, 'UTF-8'); // Replace spaces and special chars with hyphens, keep Unicode letters/numbers $id = preg_replace('/[^\p{L}\p{N}\s-]/u', '', $id); $id = preg_replace('/\s+/', '-', $id); $id = preg_replace('/-+/', '-', $id); $id = trim($id, '-'); // Ensure ID starts with letter (HTML spec requirement) if (!empty($id) && !preg_match('/^[a-z]/i', $id)) { $id = 'heading-' . $id; } // Add prefix $id = 'toc-' . $id; // Handle empty ID if (empty($id) || $id === 'toc-' || $id === 'toc-heading-') { $id = 'toc-heading-' . (count($this->used_ids) + 1); } // Handle duplicates by adding counter $original_id = $id; $counter = 2; while (in_array($id, $this->used_ids)) { $id = $original_id . '-' . $counter; $counter++; } // Store to prevent future duplicates $this->used_ids[] = $id; return $id; } /** * Build TOC HTML. * * @param array $headings Array of headings. * @return string TOC HTML. */ private function build_toc_html($headings) { if (empty($headings)) { return ''; } // Get template $template = isset($this->settings['template']) ? $this->settings['template'] : 'minimal'; // Get show toggle setting $show_toggle = isset($this->settings['show_toggle']) ? $this->settings['show_toggle'] : true; // Get sticky/floating settings $sticky_mode = isset($this->settings['sticky_mode']) ? $this->settings['sticky_mode'] : 'none'; $floating_position = isset($this->settings['floating_position']) ? $this->settings['floating_position'] : 'right'; $top_offset = isset($this->settings['top_offset']) ? absint($this->settings['top_offset']) : 20; // Build container classes $container_classes = array('smart-toc-container', 'smart-toc-template-' . esc_attr($template)); // Build inline styles for floating TOC $inline_styles = ''; if ($sticky_mode === 'sticky') { $container_classes[] = 'smart-toc-sticky'; $inline_styles = 'top: ' . $top_offset . 'px;'; } elseif ($sticky_mode === 'floating') { $container_classes[] = 'smart-toc-floating'; $container_classes[] = 'smart-toc-' . esc_attr($floating_position); $container_classes[] = 'smart-toc-visible'; // Start visible $inline_styles = 'top: ' . $top_offset . 'px; max-height: calc(100vh - ' . ($top_offset + 20) . 'px);'; } // Start TOC container $html = '
'; if ($show_toggle) { $html .= ''; } $html .= '
'; // Add TOC list $html .= ''; $html .= ''; // Add Schema.org markup for SEO $html .= $this->generate_schema_markup($headings); return $html; } /** * Generate Schema.org markup for TOC. * * @param array $headings Array of headings. * @return string JSON-LD script tag. */ private function generate_schema_markup($headings) { if (empty($headings)) { return ''; } $schema = array( '@context' => 'https://schema.org', '@type' => 'TableOfContents', 'itemListElement' => array() ); $current_url = get_permalink(); foreach ($headings as $index => $heading) { $schema['itemListElement'][] = array( '@type' => 'ListItem', 'position' => $index + 1, 'name' => $heading['text'], 'url' => $current_url . '#' . $heading['id'] ); } return ''; } /** * Check if TOC should be displayed based on conditional rules. * * @return bool True if TOC should be displayed. */ private function should_display_toc() { global $post; if (!$post) { return false; } // Check post type restrictions $allowed_post_types = isset($this->settings['post_types']) ? $this->settings['post_types'] : array('post', 'page'); if (!empty($allowed_post_types) && !in_array($post->post_type, $allowed_post_types)) { return false; } // Check excluded posts/pages $excluded_ids = isset($this->settings['excluded_ids']) ? $this->settings['excluded_ids'] : ''; if (!empty($excluded_ids)) { $excluded_array = array_map('trim', explode(',', $excluded_ids)); if (in_array($post->ID, $excluded_array)) { return false; } } // Check category restrictions (for posts) if ($post->post_type === 'post') { $excluded_categories = isset($this->settings['excluded_categories']) ? $this->settings['excluded_categories'] : array(); if (!empty($excluded_categories)) { $post_categories = wp_get_post_categories($post->ID); if (array_intersect($post_categories, $excluded_categories)) { return false; } } } // Check minimum word count $min_words = isset($this->settings['min_word_count']) ? (int) $this->settings['min_word_count'] : 0; if ($min_words > 0) { $word_count = str_word_count(strip_tags($post->post_content)); if ($word_count < $min_words) { return false; } } // Check device type (mobile/desktop) $hide_on_mobile = isset($this->settings['hide_on_mobile']) ? $this->settings['hide_on_mobile'] : false; if ($hide_on_mobile && wp_is_mobile()) { return false; } // Check user role restrictions $allowed_roles = isset($this->settings['allowed_roles']) ? $this->settings['allowed_roles'] : array(); if (!empty($allowed_roles)) { $user = wp_get_current_user(); if (empty($user->roles) || empty(array_intersect($user->roles, $allowed_roles))) { return false; } } return true; } /** * TOC shortcode handler. * * @param array $atts Shortcode attributes. * @return string TOC HTML. */ public function toc_shortcode($atts) { global $post; if (!$post) { return ''; } // Generate TOC for current post content $toc = $this->generate_toc($post->post_content); return $toc; } }