db = $db; } /** * Titles of other posts that already target this keyword. * * @param string $keyword Keyword to look for. * @param int $excludePostId Post being edited, left out of the result. * @return string[] Post titles, capped and de-duplicated. */ public function usedElsewhere( string $keyword, int $excludePostId ): array { $keyword = trim( $keyword ); $db = $this->connection(); if ( '' === $keyword || null === $db ) { return []; } $meta_table = (string) $db->postmeta; $posts_table = (string) $db->posts; $user_id = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0; // Only published posts or the current user's own posts can own a keyword. // Trashed, auto-draft and inherit rows never warn, and never leak a title. $sql = 'SELECT pm.post_id FROM ' . $meta_table . ' pm' . ' INNER JOIN ' . $posts_table . ' p ON p.ID = pm.post_id' . ' WHERE pm.meta_key = %s' . ' AND pm.meta_value LIKE %s' . ' AND pm.post_id != %d' . " AND p.post_status NOT IN ('trash', 'auto-draft', 'inherit')" . ' AND ( p.post_status = %s OR p.post_author = %d )' . ' LIMIT %d'; $ids = $db->get_col( $db->prepare( $sql, self::META_KEY, '%' . $db->esc_like( $keyword ) . '%', $excludePostId, 'publish', $user_id, self::LIMIT ) ); if ( ! is_array( $ids ) ) { return []; } $ids = array_values( array_filter( array_map( 'intval', $ids ), static fn ( int $id ): bool => $id > 0 ) ); // One priming call instead of one query per title in the loop below. if ( [] !== $ids && function_exists( '_prime_post_caches' ) ) { _prime_post_caches( $ids ); } $titles = []; foreach ( $ids as $id ) { $title = get_the_title( (int) $id ); if ( is_string( $title ) && '' !== $title ) { $titles[] = $title; } } return array_values( array_unique( $titles ) ); } /** * Active connection, or null when the database is unavailable. * * @return \wpdb|null The result. */ private function connection() { if ( null !== $this->db ) { return $this->db; } global $wpdb; if ( ! isset( $wpdb ) || ! is_object( $wpdb ) ) { return null; } return $wpdb; } }