Open for Freelance & Projects
f in yt wp

Zero-Plugin AI Internal Link Suggester in WordPress Using Pure PHP & Cosine Similarity

Abdullah Nahian Updated: November 29, 2026 Reading Time: 6 mins

Zero-Plugin AI Internal Link Suggester in WordPress Using Pure PHP & Cosine Similarity

Keyword matching and shared tags miss plenty of relevant internal links because two articles can cover the same topic with different wording. A guide on database deadlocks and a tutorial on slow WooCommerce queries belong together in your internal link graph even when they share zero tags.

You can build a zero-plugin internal link suggester right inside your theme using WordPress’s built-in wp_remote_post() function, post meta storage, and pure PHP cosine similarity. No extra plugins, no external vector database, and no bloated runtime overhead.

Core Idea: Turn each post’s title, excerpt, and body into a compact embedding vector on save, store it in post meta, and rank candidate posts in pure PHP using cosine similarity.

LayerWordPress PrimitiveRole in the Linker
Embeddingswp_remote_post() + md5() hashGenerates vectors on publish/update only when content changes
Storageupdate_post_meta() (512 dims)Keeps vectors close to each post with low database footprint
RankingPure PHP cosine similarityScores semantic closeness across published posts and skips existing links

How Pure PHP Cosine Similarity Ranks Posts

Embeddings map text into a list of numbers where topically similar posts point in a similar direction. Cosine similarity measures the angle between two vectors on a scale from -1.0 to 1.0 by dividing their dot product by the product of their Euclidean magnitudes.

  • Skip unchanged content: Hash the normalized title, excerpt, and trimmed body text so routine status or category tweaks do not trigger unnecessary API calls.
  • Keep vectors compact: Requesting 512 dimensions trims serialized meta size and loop time while preserving strong semantic ranking.
  • Filter out already-linked URLs: Check whether the candidate post’s permalink already appears in the current post content before surfacing it as a new opportunity.

Pure PHP Cosine Similarity & Suggestion Engine

Drop this class into your theme’s inc/ directory and load it from functions.php after defining your embedding API key in wp-config.php.

<?php
final class DNTH_AI_Internal_Linker {

	private const META_VECTOR = '_dnth_ai_embedding_vec';
	private const META_HASH   = '_dnth_ai_embedding_hash';
	private const DIMENSIONS  = 512;

	public static function init(): void {
		add_action( 'save_post_post', array( __CLASS__, 'maybe_generate_embedding' ), 20, 2 );
		add_action( 'add_meta_boxes', array( __CLASS__, 'register_metabox' ) );
	}

	public static function maybe_generate_embedding( int $post_id, WP_Post $post ): void {
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}
		if ( wp_is_post_revision( $post_id ) || 'publish' !== $post->post_status ) {
			return;
		}

		$text = self::prepare_text( $post );
		if ( '' === $text ) {
			return;
		}

		$hash = md5( $text );
		if ( $hash === (string) get_post_meta( $post_id, self::META_HASH, true ) ) {
			return;
		}

		$vec = self::fetch_embedding( $text );
		if ( ! is_wp_error( $vec ) ) {
			update_post_meta( $post_id, self::META_VECTOR, $vec );
			update_post_meta( $post_id, self::META_HASH, $hash );
		}
	}

	private static function prepare_text( WP_Post $post ): string {
		$body = wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 600, '' );
		return trim( $post->post_title . "\n\n" . $post->post_excerpt . "\n\n" . $body );
	}

	private static function fetch_embedding( string $text ) {
		$key = defined( 'DNTH_OPENAI_API_KEY' ) ? DNTH_OPENAI_API_KEY : '';
		if ( '' === $key ) {
			return new WP_Error( 'dnth_no_key', 'Missing embedding API key.' );
		}

		$res = wp_remote_post(
			'https://api.openai.com/v1/embeddings',
			array(
				'timeout' => 15,
				'headers' => array(
					'Authorization' => 'Bearer ' . $key,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'model'      => 'text-embedding-3-small',
						'input'      => $text,
						'dimensions' => self::DIMENSIONS,
					)
				),
			)
		);

		if ( is_wp_error( $res ) || 200 !== wp_remote_retrieve_response_code( $res ) ) {
			return new WP_Error( 'dnth_embed_err', 'Embedding request failed.' );
		}

		$data = json_decode( wp_remote_retrieve_body( $res ), true );
		return ! empty( $data['data'][0]['embedding'] )
			? array_map( 'floatval', $data['data'][0]['embedding'] )
			: new WP_Error( 'dnth_embed_empty', 'Empty vector returned.' );
	}

	public static function cosine_similarity( array $a, array $b ): float {
		$len = count( $a );
		if ( 0 === $len || $len !== count( $b ) ) {
			return 0.0;
		}

		$dot = $mag_a = $mag_b = 0.0;
		for ( $i = 0; $i < $len; $i++ ) {
			$dot   += $a[ $i ] * $b[ $i ];
			$mag_a += $a[ $i ] * $a[ $i ];
			$mag_b += $b[ $i ] * $b[ $i ];
		}

		$denom = sqrt( $mag_a ) * sqrt( $mag_b );
		return $denom > 0.0 ? ( $dot / $denom ) : 0.0;
	}

	public static function get_suggestions( int $post_id, int $limit = 5, float $min_score = 0.45 ): array {
		$post       = get_post( $post_id );
		$source_vec = get_post_meta( $post_id, self::META_VECTOR, true );
		if ( ! $post || ! is_array( $source_vec ) ) {
			return array();
		}

		global $wpdb;
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT p.ID, p.post_title, pm.meta_value
				 FROM {$wpdb->posts} p
				 INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
				 WHERE p.post_type = 'post' AND p.post_status = 'publish'
				   AND p.ID != %d AND pm.meta_key = %s",
				$post_id,
				self::META_VECTOR
			)
		);

		$matches = array();
		foreach ( $rows as $row ) {
			$target_vec = maybe_unserialize( $row->meta_value );
			if ( ! is_array( $target_vec ) ) {
				continue;
			}
			$score = self::cosine_similarity( $source_vec, $target_vec );
			if ( $score >= $min_score ) {
				$url       = get_permalink( (int) $row->ID );
				$matches[] = array(
					'title'          => $row->post_title,
					'url'            => $url,
					'score'          => round( $score * 100, 1 ),
					'already_linked' => false !== strpos( $post->post_content, $url ),
				);
			}
		}

		usort( $matches, static fn( $x, $y ) => $y['score'] <=> $x['score'] );
		return array_slice( $matches, 0, $limit );
	}

	public static function register_metabox(): void {
		add_meta_box( 'dnth-ai-links', 'AI Internal Link Suggestions', array( __CLASS__, 'render_metabox' ), 'post', 'side' );
	}

	public static function render_metabox( WP_Post $post ): void {
		$items = self::get_suggestions( $post->ID );
		if ( ! $items ) {
			echo '<p>Save a published post once other embedded posts exist to see matches.</p>';
			return;
		}
		foreach ( $items as $item ) {
			$badge = $item['already_linked'] ? ' (Already linked)' : '';
			printf(
				'<p><strong>%s%%</strong>%s<br><a href="%s" target="_blank" rel="noopener">%s</a></p>',
				esc_html( $item['score'] ),
				esc_html( $badge ),
				esc_url( $item['url'] ),
				esc_html( $item['title'] )
			);
		}
	}
}
DNTH_AI_Internal_Linker::init();

Scaling & Editorial Workflow Tips

  1. Tune your similarity threshold: Start around 0.45 and raise or lower it based on how tightly focused your blog categories are.
  2. Backfill older posts in batches: Run a small CLI or admin batch script over existing published posts so new articles can immediately compare against your archive.
  3. Keep links natural: Use semantic similarity to find the right target article, then write descriptive anchor text inside a relevant paragraph rather than stuffing link lists.

Quick FAQ

Does this require a vector database plugin or Node build step?

No. It runs purely in PHP using standard WordPress post meta and HTTP requests, making it easy to maintain inside a custom theme.

Will saving a draft or updating a category burn API credits?

No. The hook skips autosaves and non-published statuses, and compares an md5() content hash before calling the embeddings endpoint.