get_editor_settings() ); } /** * Add Classic Editor assets on post editing screens. * * @param string $hook Current admin hook. */ public function enqueue_classic_editor_assets($hook) { if (!in_array($hook, array('post.php', 'post-new.php'), true)) { return; } $script_path = SKYINPO_PLUGIN_PATH . 'assets/js/classic-editor.js'; $style_path = SKYINPO_PLUGIN_PATH . 'assets/css/classic-editor.css'; wp_register_script( 'skyinpo-internal-post-linker-classic-editor', SKYINPO_PLUGIN_URL . 'assets/js/classic-editor.js', array(), file_exists($script_path) ? filemtime($script_path) : SKYINPO_VERSION, false ); wp_add_inline_script( 'skyinpo-internal-post-linker-classic-editor', 'window.skyinpo_InternalPostLinkerClassic = ' . wp_json_encode($this->get_editor_settings()) . ';', 'before' ); wp_enqueue_script('skyinpo-internal-post-linker-classic-editor'); wp_enqueue_style( 'skyinpo-internal-post-linker-classic-editor', SKYINPO_PLUGIN_URL . 'assets/css/classic-editor.css', array(), file_exists($style_path) ? filemtime($style_path) : SKYINPO_VERSION ); } /** * Register the TinyMCE plugin script. * * @param array $plugins TinyMCE plugins. * @return array */ public function register_tinymce_plugin($plugins) { if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) { return $plugins; } $plugins['skyinpo_internal_post_linker'] = SKYINPO_PLUGIN_URL . 'assets/js/classic-editor.js'; return $plugins; } /** * Register the TinyMCE toolbar button. * * @param string[] $buttons TinyMCE buttons. * @return string[] */ public function register_tinymce_button($buttons) { if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) { return $buttons; } $link_position = array_search('link', $buttons, true); if (false === $link_position) { $buttons[] = 'skyinpo_internal_post_linker'; return $buttons; } array_splice($buttons, $link_position + 1, 0, 'skyinpo_internal_post_linker'); return $buttons; } /** * Return shared editor settings. * * @return array */ private function get_editor_settings() { return array( 'searchPath' => '/' . $this->namespace . '/search', 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('skyinpo_search_posts'), 'suggestNonce' => wp_create_nonce('skyinpo_suggest_links'), 'currentPostId' => get_the_ID() ? absint(get_the_ID()) : 0, 'minSearchLength' => 2, 'searchTimeoutMs' => 8000, 'suggestionLimit' => 20, ); } /** * Register REST routes used by the editor UI. */ public function register_rest_routes() { register_rest_route( $this->namespace, '/search', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this, 'search_posts'), 'permission_callback' => array($this, 'can_search_posts'), 'args' => array( 'term' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => '', ), 'post_id' => array( 'type' => 'integer', 'sanitize_callback' => 'absint', 'default' => 0, ), ), ) ); } /** * Confirm the current user can use the post editor. * * @return bool */ public function can_search_posts() { return current_user_can('edit_posts'); } /** * Search linkable posts over admin-ajax for editor requests. */ public function ajax_search_posts() { check_ajax_referer('skyinpo_search_posts', 'nonce'); if (!$this->can_search_posts()) { wp_send_json_error( array('message' => __('You are not allowed to search posts.', '7sky-internal-post-linker')), 403 ); } $results = $this->get_search_results( isset($_GET['term']) ? sanitize_text_field(wp_unslash($_GET['term'])) : '', isset($_GET['post_id']) ? absint(wp_unslash($_GET['post_id'])) : 0 ); wp_send_json_success($results); } /** * Suggest internal links for the current editor content. */ public function ajax_suggest_links() { check_ajax_referer('skyinpo_suggest_links', 'nonce'); if (!$this->can_search_posts()) { wp_send_json_error( array('message' => __('You are not allowed to scan posts.', '7sky-internal-post-linker')), 403 ); } $content = isset($_POST['content']) ? wp_kses_post(wp_unslash((string) $_POST['content'])) : ''; $current_post_id = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0; wp_send_json_success($this->get_link_suggestions($content, $current_post_id)); } /** * Render a Classic Editor publish-box entry for link suggestions. */ public function render_classic_suggestion_button() { if (!$this->can_search_posts()) { return; } printf( '
', esc_html__('Suggest internal links', '7sky-internal-post-linker') ); } /** * Search linkable internal content. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function search_posts(WP_REST_Request $request) { $term = trim((string) $request->get_param('term')); $current_post_id = absint($request->get_param('post_id')); return rest_ensure_response($this->get_search_results($term, $current_post_id)); } /** * Get search results for REST and admin-ajax requests. * * @param string $term Search term. * @param int $current_post_id Current editor post ID. * @return array> */ private function get_search_results($term, $current_post_id) { $term = trim((string) $term); $current_post_id = absint($current_post_id); if (strlen($term) < 2) { return array(); } $post_types = $this->get_searchable_post_types(); if (empty($post_types)) { return array(); } $post_statuses = array('publish'); if (current_user_can('read_private_posts')) { $post_statuses[] = 'private'; } $query = new WP_Query( array( 's' => $term, 'post_type' => $post_types, 'post_status' => $post_statuses, 'posts_per_page' => 8, 'orderby' => 'modified', 'order' => 'DESC', 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'search_columns' => array('post_title', 'post_name'), ) ); $results = array(); foreach ($query->posts as $post) { $results[] = array( 'id' => (int) $post->ID, 'title' => html_entity_decode(get_the_title($post), ENT_QUOTES, get_bloginfo('charset')), 'type' => $this->get_post_type_label($post->post_type), 'postType' => $post->post_type, 'url' => get_permalink($post), 'status' => $post->post_status, 'isCurrent' => $current_post_id === (int) $post->ID, 'date' => get_the_date('', $post), 'excerpt' => $this->get_result_excerpt($post), ); } wp_reset_postdata(); return $results; } /** * Find deterministic internal-link suggestions from existing content titles and slugs. * * @param string $content Current editor content. * @param int $current_post_id Current editor post ID. * @return array> */ private function get_link_suggestions($content, $current_post_id) { $scan_text = $this->get_suggestion_scan_text($content); if (strlen($scan_text) < 20) { return array(); } $post_types = $this->get_searchable_post_types(); if (empty($post_types)) { return array(); } $post_statuses = array('publish'); if (current_user_can('read_private_posts')) { $post_statuses[] = 'private'; } $query = new WP_Query( array( 'post_type' => $post_types, 'post_status' => $post_statuses, 'posts_per_page' => 200, 'orderby' => 'modified', 'order' => 'DESC', 'no_found_rows' => true, 'ignore_sticky_posts' => true, ) ); $suggestions = array(); $seen = array(); foreach ($query->posts as $post) { $phrases = $this->get_suggestion_phrases($post); foreach ($phrases as $phrase) { $count = $this->count_phrase_matches($scan_text, $phrase); if ($count < 1) { continue; } $key = strtolower($phrase) . ':' . (int) $post->ID; if (isset($seen[$key])) { continue; } $rating = $this->get_suggestion_rating($post, $phrase, $count); $seen[$key] = true; $suggestions[] = array( 'keyword' => $phrase, 'count' => $count, 'rating' => $rating['label'], 'ratingScore' => $rating['score'], 'id' => (int) $post->ID, 'title' => html_entity_decode(get_the_title($post), ENT_QUOTES, get_bloginfo('charset')), 'type' => $this->get_post_type_label($post->post_type), 'postType' => $post->post_type, 'url' => get_permalink($post), 'isCurrent' => $current_post_id === (int) $post->ID, 'date' => get_the_date('', $post), 'excerpt' => $this->get_result_excerpt($post), ); } } wp_reset_postdata(); usort( $suggestions, static function ($a, $b) { if ($a['ratingScore'] !== $b['ratingScore']) { return $b['ratingScore'] <=> $a['ratingScore']; } if ($a['count'] !== $b['count']) { return $b['count'] <=> $a['count']; } return strlen($b['keyword']) <=> strlen($a['keyword']); } ); return array_slice($suggestions, 0, 20); } /** * Rate a suggestion using deterministic match strength signals. * * @param WP_Post $post Target post. * @param string $phrase Suggested keyword. * @param int $count Keyword occurrence count in current article. * @return array{label: string, score: int} */ private function get_suggestion_rating(WP_Post $post, $phrase, $count) { $title = strtolower(html_entity_decode(get_the_title($post), ENT_QUOTES, get_bloginfo('charset'))); $slug = strtolower(str_replace(array('-', '_'), ' ', $post->post_name)); $excerpt = strtolower($this->get_result_excerpt($post)); $keyword = strtolower((string) $phrase); $word_count = str_word_count($keyword); $score = 0; if ($keyword && false !== strpos($title, $keyword)) { $score += 35; } if ($keyword && false !== strpos($slug, $keyword)) { $score += 20; } if ($keyword && false !== strpos($excerpt, $keyword)) { $score += 15; } $score += min(20, max(0, (int) $count) * 5); $score += min(20, max(0, $word_count - 1) * 5); if ($keyword === $title || $keyword === $slug) { $score += 15; } if ($score >= 85) { return array('label' => __('Ideal', '7sky-internal-post-linker'), 'score' => $score); } if ($score >= 65) { return array('label' => __('Best', '7sky-internal-post-linker'), 'score' => $score); } if ($score >= 45) { return array('label' => __('Good', '7sky-internal-post-linker'), 'score' => $score); } return array('label' => __('Normal', '7sky-internal-post-linker'), 'score' => $score); } /** * Strip linked text and markup so suggestions do not target existing links. * * @param string $content Current editor content. * @return string */ private function get_suggestion_scan_text($content) { $content = preg_replace('#]*>.*?#is', ' ', $content); $content = wp_strip_all_tags(strip_shortcodes((string) $content)); $content = html_entity_decode($content, ENT_QUOTES, get_bloginfo('charset')); return preg_replace('/\s+/', ' ', trim($content)); } /** * Build useful non-AI match phrases from a target post. * * @param WP_Post $post Target post. * @return string[] */ private function get_suggestion_phrases(WP_Post $post) { $phrases = array(); $title = html_entity_decode(get_the_title($post), ENT_QUOTES, get_bloginfo('charset')); $slug = str_replace(array('-', '_'), ' ', $post->post_name); foreach (array($title, $slug) as $phrase) { $phrase = preg_replace('/\s+/', ' ', trim(wp_strip_all_tags((string) $phrase))); if (strlen($phrase) < 4 || str_word_count($phrase) < 2) { continue; } $phrases[strtolower($phrase)] = $phrase; foreach ($this->get_title_phrase_candidates($phrase) as $candidate) { $phrases[strtolower($candidate)] = $candidate; } } return array_values($phrases); } /** * Build shorter useful phrase candidates from a title or slug. * * @param string $phrase Full title or slug phrase. * @return string[] */ private function get_title_phrase_candidates($phrase) { $stopwords = array( 'a', 'an', 'and', 'are', 'as', 'at', 'by', 'for', 'from', 'how', 'in', 'into', 'is', 'it', 'of', 'on', 'or', 'the', 'to', 'with', 'what', 'when', 'where', 'why', 'your', ); $words = preg_split('/\s+/', $phrase); $candidates = array(); $count = count($words); $max_length = min(5, $count); for ($length = $max_length; $length >= 2; $length--) { for ($offset = 0; $offset <= $count - $length; $offset++) { $slice = array_slice($words, $offset, $length); $first = strtolower(trim($slice[0], " \t\n\r\0\x0B.,:;!?()[]{}\"'")); $last = strtolower(trim($slice[$length - 1], " \t\n\r\0\x0B.,:;!?()[]{}\"'")); $candidate = preg_replace('/[^\p{L}\p{N}\s&+-]/u', '', implode(' ', $slice)); $candidate = preg_replace('/\s+/', ' ', trim($candidate)); if (in_array($first, $stopwords, true) || in_array($last, $stopwords, true)) { continue; } if (strlen($candidate) < 4 || str_word_count($candidate) < 2) { continue; } $candidates[strtolower($candidate)] = $candidate; } } return array_values($candidates); } /** * Count whole-phrase matches in plain editor text. * * @param string $text Plain text. * @param string $phrase Candidate phrase. * @return int */ private function count_phrase_matches($text, $phrase) { $pattern = '/(? true, 'show_ui' => true, ), 'names' ); unset($post_types['attachment']); return array_values($post_types); } /** * Get a readable post type label. * * @param string $post_type Post type name. * @return string */ private function get_post_type_label($post_type) { $object = get_post_type_object($post_type); if (!$object || empty($object->labels->singular_name)) { return $post_type; } return $object->labels->singular_name; } /** * Build a compact excerpt for search results. * * @param WP_Post $post Post object. * @return string */ private function get_result_excerpt(WP_Post $post) { $raw_excerpt = has_excerpt($post) ? $post->post_excerpt : $post->post_content; $excerpt = wp_strip_all_tags(strip_shortcodes($raw_excerpt)); return html_entity_decode(wp_trim_words($excerpt, 18, '...'), ENT_QUOTES, get_bloginfo('charset')); } } skyinpo_Internal_Post_Linker::init();