Skip to content

Commit

Permalink
Caching now supports expiry
Browse files Browse the repository at this point in the history
Fixes #23
  • Loading branch information
ajaydsouza committed Mar 2, 2022
1 parent 495c1b2 commit 44800f1
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 72 deletions.
217 changes: 163 additions & 54 deletions includes/cache.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
<?php
/**
* Contextual Related Posts Cache interface.
* Cache interface.
*
* @package Contextual_Related_Posts
* @author Ajay D'Souza
* @license GPL-2.0+
* @link https://webberzone.com
* @copyright 2009-2020 Ajay D'Souza
* @package WHEREGO
*/

// If this file is called directly, abort.
Expand All @@ -21,52 +17,16 @@
*/
function wherego_ajax_clearcache() {

global $wpdb;

$counter = array();

$meta_keys = wherego_cache_get_keys();
$error = false;

foreach ( $meta_keys as $meta_key ) {

$count = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
"
DELETE FROM {$wpdb->postmeta}
WHERE meta_key = %s
",
$meta_key
wherego_cache_delete();
exit(
wp_json_encode(
array(
'success' => 1,
'message' => __( 'Cache cleared', 'where-did-they-go-from-here' ),
)
);

if ( false === $count ) {
$error = true;
} else {
$counter[] = $count;
}
}
)
);

/**** Did an error occur? */
if ( $error ) {
exit(
wp_json_encode(
array(
'success' => 0,
'message' => __( 'An error occurred clearing the cache. Please contact your site administrator.\n\nError message:\n', 'where-did-they-go-from-here' ) . $wpdb->print_error(),
)
)
);
} else { // No error, return the number of.
exit(
wp_json_encode(
array(
'success' => 1,
'message' => ( array_sum( $counter ) ) . __( ' cached row(s) cleared', 'where-did-they-go-from-here' ),
)
)
);
}
}
add_action( 'wp_ajax_wherego_clear_cache', 'wherego_ajax_clearcache' );

Expand All @@ -77,8 +37,10 @@ function wherego_ajax_clearcache() {
* @since 2.4.0
*
* @param array $meta_keys Array of meta keys that hold the cache.
* @return int Number of keys deleted.
*/
function wherego_cache_delete( $meta_keys = array() ) {
$loop = 0;

$default_meta_keys = wherego_cache_get_keys();

Expand All @@ -89,8 +51,13 @@ function wherego_cache_delete( $meta_keys = array() ) {
}

foreach ( $meta_keys as $meta_key ) {
delete_post_meta_by_key( $meta_key );
$del_meta = delete_wherego_cache_by_key( $meta_key );
if ( $del_meta ) {
$loop++;
}
}

return $loop;
}


Expand All @@ -99,10 +66,10 @@ function wherego_cache_delete( $meta_keys = array() ) {
*
* @since 2.4.0
*
* @param mixed $post_id Post ID.
* @param int $post_id Post ID. Optional.
* @return array Array of _wherego_cache keys.
*/
function wherego_cache_get_keys( $post_id = null ) {
function wherego_cache_get_keys( $post_id = 0 ) {
global $wpdb;

$keys = array();
Expand All @@ -111,9 +78,10 @@ function wherego_cache_get_keys( $post_id = null ) {
SELECT meta_key
FROM {$wpdb->postmeta}
WHERE `meta_key` LIKE '_wherego_cache_%'
AND `meta_key` NOT LIKE '_wherego_cache_expires_%'
";

if ( is_int( $post_id ) ) {
if ( $post_id > 0 ) {
$sql .= $wpdb->prepare( ' AND `post_id` = %d ', $post_id );
}

Expand Down Expand Up @@ -151,5 +119,146 @@ function wherego_cache_delete_by_post( $post_id = null ) {
$flag[] = delete_post_meta( $post_id, $meta_key );
}
return wp_json_encode( $flag );
}

/**
* Get the meta key based on a list of parameters.
*
* @since 2.4.0
*
* @param mixed $attr Array of attributes typically.
* @return string Cache meta key
*/
function wherego_cache_get_key( $attr ) {

$meta_key = md5( wp_json_encode( $attr ) );

return $meta_key;
}

/**
* Sets/updates the value of the WZP cache for a post.
*
* @since 3.0.0
*
* @param int $post_id Post ID.
* @param string $key WZP Cache key.
* @param mixed $value Metadata value. Must be serializable if non-scalar.
* @param int $expiration Time until expiration in seconds. Default WZP_CACHE_TIME (one week if not overridden).
* @return int|bool Meta ID if the key didn't exist, true on successful update,
* false on failure or if the value passed to the function
* is the same as the one that is already in the database.
*/
function set_wherego_cache( $post_id, $key, $value, $expiration = WZP_CACHE_TIME ) {

$expiration = (int) $expiration;

/**
* Filters the expiration for a WZP Cache key before its value is set.
*
* The dynamic portion of the hook name, `$key`, refers to the WZP Cache key.
*
* @since 3.0.0
*
* @param int $expiration Time until expiration in seconds. Use 0 for no expiration.
* @param int $post_id Post ID.
* @param string $key WZP Cache key name.
* @param mixed $value New value of WZP Cache key.
*/
$expiration = apply_filters( "wherego_cache_time_{$key}", $expiration, $post_id, $key, $value );

$meta_key = '_wherego_cache_' . $key;
$cache_expires = '_wherego_cache_expires_' . $key;

$updated = update_post_meta( $post_id, $meta_key, $value, '' );
update_post_meta( $post_id, $cache_expires, time() + $expiration, '' );

return $updated;
}

/**
* Get the value of the WZP cache for a post.
*
* @since 3.0.0
*
* @param int $post_id Post ID.
* @param string $key WZP Cache key.
* @return mixed Value of the WZP cache or false if invalid, expired or unavailable.
*/
function get_wherego_cache( $post_id, $key ) {
$meta_key = '_wherego_cache_' . $key;
$cache_expires = '_wherego_cache_expires_' . $key;

$value = get_post_meta( $post_id, $meta_key, true );

if ( ! WZP_CACHE_TIME ) {
return $value;
}

if ( $value ) {
$expires = (int) get_post_meta( $post_id, $cache_expires, true );
if ( $expires < time() || empty( $expires ) ) {
delete_wherego_cache( $post_id, $meta_key );
return false;
} else {
return $value;
}
} else {
return false;
}
}


/**
* Delete the value of the WZP cache for a post.
*
* @since 3.0.0
*
* @param int $post_id Post ID.
* @param string $key WZP Cache key.
* @return bool True on success, False on failure.
*/
function delete_wherego_cache( $post_id, $key ) {
$meta_key = '_wherego_cache_' . $key;
$cache_expires = '_wherego_cache_expires_' . $key;

$result = delete_post_meta( $post_id, $meta_key );
if ( $result ) {
delete_post_meta( $post_id, $cache_expires );
}

return $result;
}


/**
* Delete the value of the WZP cache by cache key.
*
* @since 3.0.0
*
* @param string $key WZP Cache key.
* @return bool True on success, False on failure.
*/
function delete_wherego_cache_by_key( $key ) {
$key = str_replace( '_wherego_cache_expires_', '', $key );
$key = str_replace( '_wherego_cache_', '', $key );
$meta_key = '_wherego_cache_' . $key;
$cache_expires = '_wherego_cache_expires_' . $key;

$result = delete_post_meta_by_key( $meta_key );
delete_post_meta_by_key( $cache_expires );

return $result;
}

/**
* Adds a clear cache button to the settings screen.
*
* @since 3.0.0
*/
function wherego_cache_button() {
?>
<input type="button" name="cache_clear" id="cache_clear" value="<?php esc_attr_e( 'Clear cache', 'where-did-they-go-from-here' ); ?>" class="button button-secondary delete" onclick="return wheregoClearCache();" />
<?php
}
add_action( 'wherego_settings_form_buttons', 'wherego_cache_button' );
19 changes: 2 additions & 17 deletions includes/main.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function get_wherego( $args = array() ) {
if ( ! empty( $args['cache'] ) && ! ( is_preview() || is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) ) {
$meta_key = wherego_cache_get_key( $args );

$output = get_post_meta( $post->ID, $meta_key, true );
$output = get_wherego_cache( $post->ID, $meta_key );
if ( $output ) {
/** This filter has been defined in main.php */
return apply_filters( 'get_wherego', $output, $args );
Expand Down Expand Up @@ -175,7 +175,7 @@ function get_wherego( $args = array() ) {

// Support caching to speed up retrieval.
if ( ! empty( $args['cache'] ) && ! ( is_preview() || is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) ) {
update_post_meta( $post->ID, $meta_key, $output, '' );
set_wherego_cache( $post->ID, $meta_key, $output );
}

/**
Expand Down Expand Up @@ -384,18 +384,3 @@ function wherego_get_style() {
*/
return apply_filters( 'wherego_get_style', $style, $wherego_style, $thumb_width, $thumb_height );
}

/**
* Get the meta key based on a list of parameters.
*
* @since 2.4.0
*
* @param array $attr Array of attributes.
* @return string Cache meta key
*/
function wherego_cache_get_key( $attr ) {

$meta_key = '_wherego_cache_' . md5( wp_json_encode( $attr ) );

return $meta_key;
}
1 change: 1 addition & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ You can also use this function to display posts on any type of page generated by
* Support for PolyLang and WPML

* Enhancements:
* Improved caching with inbuilt expiry. Use WZP_CACHE_TIME in your wp-config.php to set how long the cache should be set for. Default is one week. Setting it to `false` will disable expiry
* Upgraded post thumbnail handling: Select the thumbnail size. The plugin will also check for site icons before the default thumbnail is selected
* Upgraded settings to new Settings_API class
* Grid thumbnail style has been redone to use CSS grid and flexbox. Please pick the correct thumbnail size in the Thumbnail settings
Expand Down
3 changes: 2 additions & 1 deletion uninstall.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ function wherego_delete_data() {
"
DELETE FROM {$wpdb->postmeta}
WHERE meta_key LIKE 'wheredidtheycomefrom'
"
OR `meta_key` LIKE '_wherego_cache_%'
"
);

delete_option( 'ald_wherego_settings' );
Expand Down
11 changes: 11 additions & 0 deletions where-did-they-go-from-here.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@
define( 'WHEREGO_PLUGIN_URL', plugin_dir_url( WHEREGO_PLUGIN_FILE ) );
}

/**
* Cache expiration time.
*
* @since 3.0.0
*
* @var int Cache time. Default is one week.
*/
if ( ! defined( 'WZP_CACHE_TIME' ) ) {
define( 'WZP_CACHE_TIME', WEEK_IN_SECONDS );
}

/*
*----------------------------------------------------------------------------
* Includes
Expand Down

0 comments on commit 44800f1

Please sign in to comment.