$post_types, 'post_status' => 'publish', 'posts_per_page' => 500, // Limit for performance. 'orderby' => 'modified', 'order' => 'DESC', 'no_found_rows' => true, 'fields' => 'ids', ); /** * Filter query args for available links. * * @since 1.0.0 * @param array $args Query args. * @param int $exclude_post_id Excluded post ID. */ $args = apply_filters( 'aiil_available_links_args', $args, $exclude_post_id ); $query = new WP_Query( $args ); $links = array(); if ( $query->have_posts() ) { foreach ( $query->posts as $post_id ) { // Filter out excluded post manually to avoid post__not_in performance issues. if ( $exclude_post_id && absint( $post_id ) === absint( $exclude_post_id ) ) { continue; } $links[] = array( 'id' => $post_id, 'title' => get_the_title( $post_id ), 'url' => get_permalink( $post_id ), 'type' => get_post_type( $post_id ), ); } } // Cache for 1 hour. set_transient( $cache_key, $links, HOUR_IN_SECONDS ); return $links; } /** * Clear available links cache. * * @param int $post_id Post ID. */ public static function clear_cache( $post_id = 0 ) { global $wpdb; if ( $post_id ) { delete_transient( 'aiil_available_links_' . $post_id ); } else { // Clear all cached links. // Check cache first to avoid unnecessary DB query. $cache_key = 'aiil_transient_cleanup_' . gmdate( 'Y-m-d-H' ); $cached = wp_cache_get( $cache_key, 'aiil_cache' ); if ( false === $cached ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Cache cleared intentionally, query runs max once per hour. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( '_transient_aiil_available_links_' ) . '%' ) ); // Cache this cleanup action for 1 hour to prevent repeated queries. wp_cache_set( $cache_key, true, 'aiil_cache', HOUR_IN_SECONDS ); } } } } // Clear cache when posts are updated. add_action( 'save_post', array( 'AIIL_Content_Analyzer', 'clear_cache' ) ); add_action( 'deleted_post', array( 'AIIL_Content_Analyzer', 'clear_cache' ) );