Home Forums Bug Reports Preview with ACF fields are incorrect Reply To: Preview with ACF fields are incorrect

  • Hey everyone,

    Not sure why ACF hasn’t put more priority on this annoying issue, since it’s been going on for years. That said, I’ve created a workaround. It’s super hacky and not ideal, but it works.

    Basically what this does is intercept the Preview button’s click event, sends the form data to an Ajax function that creates an autosave, and once that’s done it triggers a click on the Preview button. After the first click it removes itself, so it’ll only do this once.

    Here’s the javascript that needs to be included in the admin area:

    jQuery( ( $ ) => {
    	let previewBtn = $( '#preview-action .preview' );
    	if ( previewBtn.length ) {
    		let previewIntercept = $( '<span id="preview-action--trigger" style="position: absolute; left: -1px; right: -1px; top: -1px; bottom: -1px;"></span>' );
    		previewBtn.css( 'position', 'relative' ).append( previewIntercept ); ( e ) => {
    			const formData = new FormData( $( '#post' )[0] );
    			formData.set( 'action', 'create-preview-autosave' );
    			$.ajax( {
    				url: ajaxurl,
    				method: 'post',
    				data: formData,
    				cache: false,
    				contentType: false,
    				processData: false,
    				success: () => {
    					previewBtn.trigger( 'click' );
    			} );
    		} );
    } );

    And here’s the WP Ajax function that should go in functions.php or wherever you want:

    add_action( 'wp_ajax_create-preview-autosave', function() {
    	wp_create_post_autosave( $_POST );
    	header( 'HTTP/1.1 200 OK' );
    } );