secret

Fixes 'preview changes' in WordPress so that post meta is not pushed live but any modifications are available to the preview.

  • Download Gist
wp-preview-changes-meta-fix.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
<?php
 
// post meta for previews
class wp_preview_meta {
 
private $doing_preview = false;
 
public function __construct() {
add_filter( 'add_post_metadata', array( $this, 'add' ), 10, 5 );
add_filter( 'update_post_metadata', array( $this, 'update' ), 10, 5 );
add_filter( 'delete_post_metadata', array( $this, 'delete' ), 10, 5 );
add_filter( 'get_post_metadata', array( $this, 'get' ), 10, 4 );
}
 
public function is_preview() {
if( is_admin() )
return !$this->doing_preview && isset($_POST[ 'wp-preview' ]) && $_POST['wp-preview'] == 'dopreview';
 
// And on the front end: (props @yrosen)
return ! $this->doing_preview && isset( $_GET[ 'preview' ] ) && $_GET[ 'preview' ] == 'true';
}
 
private function mod_key( $key ) {
if ( strlen( $key ) > 50 )
$key = md5( $key );
return "_preview__{$key}";
}
 
public function __call( $method, $args ) {
if ( ! $this->is_preview() || ! function_exists( "{$method}_metadata" ) )
return $args[0];
 
// replace $check with $meta_type
$args[ 0 ] = 'post';
 
// modify key
$args[ 2 ] = $this->mod_key( $args[ 2 ] );
 
// call original function but make sure we don't get stuck in a loop
$this->doing_preview = true;
$result = call_user_func_array( "{$method}_metadata", $args );
$this->doing_preview = false;
 
return $result;
}
 
}
 
$wp_preview_meta = new wp_preview_meta();

This is great! Fixes a problem that's been driving me crazy.

One suggestion...is_preview() doesn't always work right. I fixed it with this:

public function is_preview() {
    if(is_admin()) {
        return !$this->doing_preview && isset($_POST[ 'wp-preview' ]) && $_POST['wp-preview'] == 'dopreview';
    }

    // And on the front end:
    return !$this->doing_preview && isset($_GET['preview']) && $_GET['preview'] == 'true';
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.