prefix . 'ailm_link_monitor'; // 1. Clear old records for this post to avoid duplicates on re-scan // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->delete( $table_name, array( 'post_id' => $post_id ), array( '%d' ) ); $post = get_post( $post_id ); if ( ! $post ) { return; } $links_to_insert = array(); $home_url = untrailingslashit( home_url() ); // 2. Find "Manual" links in the raw content $content = $post->post_content; // FIX: Escaped quotes in regex if ( preg_match_all( '/]*href=[\'"]([^\'" ]+)[\'"][^>]*>(.*?)<\/a>/is', $content, $matches ) ) { foreach ( $matches[1] as $index => $url ) { $url = trim( html_entity_decode( $url ) ); // Skip anchor links, emails, tel, and empty hrefs if ( empty( $url ) || strpos( $url, 'http' ) !== 0 ) { continue; } // Determine link type (internal or external) $is_internal = ( strpos( $url, $home_url ) === 0 ); $link_type = $is_internal ? 'internal' : 'external'; $anchor = wp_strip_all_tags( $matches[2][$index] ); // Avoid duplicates within the same post $hash = md5( $url . $anchor ); $links_to_insert[$hash] = array( 'post_id' => $post_id, 'url' => esc_url_raw( $url ), 'anchor' => sanitize_text_field( $anchor ), 'link_origin' => 'manual', 'link_type' => $link_type, 'status_code' => 0, // 0 = pending check 'last_checked'=> '0000-00-00 00:00:00' ); } } // 3. Find dynamic plugin links (AILM) in the frozen map $frozen_map = get_post_meta( $post_id, '_ailm_frozen_map', true ); if ( is_array( $frozen_map ) && ! empty( $frozen_map ) ) { foreach ( $frozen_map as $item ) { if ( empty( $item['url'] ) ) continue; $hash = md5( $item['url'] . $item['word'] . 'ailm' ); $links_to_insert[$hash] = array( 'post_id' => $post_id, 'url' => esc_url_raw( $item['url'] ), 'anchor' => sanitize_text_field( $item['word'] ), 'link_origin' => 'ailm', 'link_type' => 'internal', // AILinkMaster links are always internal 'status_code' => 0, 'last_checked'=> '0000-00-00 00:00:00' ); } } // 4. Insert all found links into the database if ( ! empty( $links_to_insert ) ) { foreach ( $links_to_insert as $data ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->insert( $table_name, $data, array( '%d', '%s', '%s', '%s', '%s', '%d', '%s' ) ); } } } }