0

So I'm using the $wp_customize to change many things in a theme, and as a result I'm wanting to set a transient for the generated CSS. I'm trying to find a flow that won't cache temporary results though, which is happening when a user plays around with settings and then hits "Cancel" - those results are still caching!

Right now I have a hacky method of setting the transient to live for just 1 second, but I feel there must be a better hook or something to grab onto. Here's my basic flow now:

    add_action( 'customize_register', array( $this, 'customize_register' ) );
    add_action( 'wp_head', array( $this, 'display_css_output' ), 99 );
    add_action( 'customize_preview_init', array( $this, 'css_cache_reset' ) );

customize_register takes care of all the settings.

function display_css_output( $short_life = 0 ) {
    $html = get_transient( 'my_custom_styles' );
    if ( empty( $html ) ) {
        $html = $this->generate_css_output();
        set_transient( 
            'my_custom_styles', 
            $html, 
            ( $short_life == 0 ? DAY_IN_SECONDS * 2 : 1 )
        );
    }
    echo $html;
}

This grabs transient if its set or otherwise goes through long process of generating the styles. Here also is my attempt at preventing the transient from persisting, $short_life which is included during another call to this function later.

function css_cache_reset() {
    delete_transient( 'my_custom_styles' );
    $this->display_css_output( $short_life = 1 );
}

There is the delete event and the call to make the transient only last 1 second.

Surely there is a better way?

2

This seems to work, modifying the display_css_output() in this way:

function display_css_output() {
    $html = get_transient( 'my_custom_styles' );
    if ( empty( $html ) ) {
        $html = $this->generate_css_output();
        global $wp_customize;
        if ( ! isset( $wp_customize ) ) {
            set_transient( 'my_custom_styles', $html, DAY_IN_SECONDS );
        }
    }
    echo $html;
}

$short_life no longer needed. Basically check to see if $wp_customize is set, don't bother setting transient then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.