// دالة لربط الوسوم في محتوى المقال فقط مع تجنب العناوين function auto_link_tags_in_content($content){if (!is_single()) return $content;// الحصول على الوسوم الخاصة بالمقال $tags=get_the_tags();if (!$tags) return $content;// تقسيم المحتوى إلى أجزاء باستخدام العناوين $parts=preg_split('/(<h[1-6][^>]*>.*?<\/h[1-6]>)/i',$content,-1,PREG_SPLIT_DELIM_CAPTURE);foreach ($parts as $key=>$part){// تجاهل الأجزاء التي تحتوي على عناوين if (preg_match('/^<h[1-6]/i',$part)){continue}// معالجة المحتوى فقط (غير العناوين) foreach ($tags as $tag){// تجنب الكلمات القصيرة جداً if (strlen($tag->name) < 3) continue;// البحث عن الكلمة في المحتوى $pattern='/\b(' . preg_quote($tag->name,'/') . ')\b/ui';// التأكد من عدم وجود الكلمة داخل رابط أو وسوم HTML $replacement=function($matches) use ($tag,$part){// التحقق من وجود الكلمة داخل وسم HTML $pre_content=substr($part,max(0, strpos($part, $matches[0]) - 300),300);if (strpos($pre_content,'<a') !==false || strpos($pre_content,'<img') !==false || strpos($pre_content,'<strong') !==false || strpos($pre_content,'<em') !==false){return $matches[0]}// إنشاء الرابط return '<a href="' . get_tag_link($tag->term_id) . '" title="' . esc_attr($tag->name) . '">' . $matches[1] . '</a>'};// استبدال أول ظهور للكلمة فقط $parts[$key]=preg_replace_callback($pattern,$replacement,$part,1)}}// إعادة دمج المحتوى return implode('',$parts)}add_filter('the_content','auto_link_tags_in_content',99);// منع الربط المتكرر للكلمة نفسها function prevent_duplicate_tag_links($content){if (!is_single()) return $content;// إيجاد جميع الروابط في المحتوى preg_match_all('/<a[^>]+>([^<]+)<\/a>/i',$content,$matches);if (!empty($matches[1])){$linked_words=array_unique($matches[1]);foreach ($linked_words as $word){// عدد مرات تكرار الكلمة كرابط $count=substr_count($content,'<a[^>]+>' . $word . '</a>');if ($count>1){// الإبقاء على أول رابط فقط $pattern='/(<a[^>]+>' . preg_quote($word,'/') . '<\/a>)/i';$content=preg_replace($pattern,'$1',$content,1);// إزالة باقي الروابط مع الإبقاء على النص $pattern='/<a[^>]+>' . preg_quote($word,'/') . '<\/a>/i';$content=preg_replace($pattern,$word,$content)}}}return $content}add_filter('the_content','prevent_duplicate_tag_links',100);// تحسين أداء البحث عن الوسوم function optimize_tag_search(){global $wpdb;$wpdb->query("ALTER TABLE $wpdb->terms ADD FULLTEXT IF NOT EXISTS search(name)");$wpdb->query("ALTER TABLE $wpdb->term_taxonomy ADD INDEX IF NOT EXISTS term_id_taxonomy(term_id, taxonomy)")}register_activation_hook(__FILE__,'optimize_tag_search');