epl_listing_query_cache(): cache a listing query until listings change
Description #
Runs a database query about listings and saves the result until a listing changes. EPL uses it for the search dropdown values and the location list. Use it in an add-on or custom search field for a query whose result only changes when listings change, such as all the values of a listing field. See How the listing search cache works.
Usage #
$values = epl_listing_query_cache( $sql, $return_type );
Parameters #
$sql (string)
A prepared SQL query (use $wpdb->prepare()). The query text is the cache key, so the same query shares one saved result.
$return_type (string)
'col' (default) returns $wpdb->get_col(): the first column of each row. 'results' returns $wpdb->get_results(): each row as an object.
Returns an array, empty when nothing is found or the query fails.
How it works #
- Within one page load, the same query runs once.
- The result is saved as a transient for 12 hours (epl_listing_query_cache_expiration).
- The query is remembered (up to 300, dropped after 14 days unused) so the background rebuild refreshes it when a listing changes. Visitors keep getting the saved result until the rebuild finishes, for up to 10 minutes (epl_listing_query_cache_stale_limit).
- When the cache is off (epl_listing_query_cache_enabled), the query runs on every page load.
Examples #
All the builder names saved on published properties, for a custom search dropdown:
function my_get_listing_builders() {
global $wpdb;
$sql = $wpdb->prepare(
"SELECT DISTINCT pm.meta_value FROM {$wpdb->postmeta} pm
INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
WHERE pm.meta_key = %s AND p.post_status = %s AND p.post_type = %s
AND pm.meta_value != ''
ORDER BY pm.meta_value",
'my_builder_name',
'publish',
'property'
);
return epl_listing_query_cache( $sql );
}
Rows as objects:
global $wpdb;
$rows = epl_listing_query_cache(
$wpdb->prepare( "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s", 'rental', 'publish' ),
'results'
);
foreach ( $rows as $row ) {
echo esc_html( $row->post_title );
}
Only cache queries whose result changes when listings change. Don't use it for queries that depend on the visitor, the date or time (such as NOW()), or on data other than listings. Changes to hidden fields (meta keys starting with an underscore) don't refresh the cache, so give fields you search on a key without one, or see epl_listing_query_cache_ignores_meta_key.
Source #
lib/includes/functions.php, in epl_listing_query_cache(). Since 3.6.