Check the stored / cached WP_Query with transients on post change

right now I have WP_Query stored for 24h (1day) with set_transient function. Everything works fine like it should. But if for example I change the post which is in the stored array to private or modify its meta_value, the post will still be seen on frontend.

Any way to check if the post values have been modified? or I should use some other function for that?

The code:

if (false === ($loop = get_transient('randomizeProfiles'))) {
    $loop = new WP_Query(array(
        'post_type' = 'portfolio',
        'posts_per_page' = 18,
        'orderby' = 'rand',
        'order' = 'ASC',
        'post_status' = 'publish',
        'meta_query' = array(
            'relation' = 'OR',
            array('key' = 'move_to_archive','compare' = 'NOT EXISTS'),
            array('key' = 'move_to_archive', 'value' = '0', 'compare' = '=')
        )
    ));
    $hour = carbon_get_theme_option('posts_hours');
    $time = 60 * 60 * $hour;
    set_transient('randomizeProfiles', $loop, $time);
}

Topic transient private loop wp-query cache Wordpress

Category Web


Use the save_post hook to check if a post that is being saved is a portfolio page and reset the transient.

add_action( 'save_post', 'reset_portfolio_transient', 10,3 );

function reset_portfolio_transient( $post_id, $post, $update ) {
    // Only set for portfolio post_type
    if ( 'portfolio' !== get_post_type($post) ) {
        return;
    }

    // delete old tranisent
    delete_transient( 'randomizeProfiles' );

    // reset your transient
    set_portfolio_query_tranisent();
}

set_portfolio_query_tranisent() being the code you already provided.

If you edit portfolio pages often this is not a great solution. You might want to read the wordpress codex on transients for an alternative.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.