Skip to content

Commit 6341c01

Browse files
committed
Add simple auto-persist for template overrides
1 parent 9aa31d2 commit 6341c01

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

classes/class-cpt-wplf-form.php

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -508,8 +508,10 @@ function maybe_load_imported_template( $post_type, $post ) {
508508
*
509509
* @return void
510510
*/
511-
protected function override_form_template( $template_content ) {
512-
// Make the editor textarea uneditable. Also remove TinyMCE.
511+
protected function override_form_template( $template_content, $form_id ) {
512+
$this->maybe_persist_override_template( $template_content, $form_id );
513+
514+
// Make the editor textarea uneditable.
513515
add_filter( 'the_editor', function ( $editor ) {
514516
if ( ! preg_match( '%id="wp-content-editor-container"%', $editor ) ) {
515517
return $editor;
@@ -547,6 +549,41 @@ protected function override_form_template( $template_content ) {
547549
} );
548550
}
549551

552+
/**
553+
* Check if we need to auto-persist the form template override into WP database.
554+
*
555+
* @param string $template Template to maybe persist.
556+
* @param int $form_id Form ID to persist template for.
557+
* @param bool $force Force a persist even though not required?
558+
*
559+
* @return void
560+
*/
561+
protected function maybe_persist_override_template( $template, $form_id, $force = false )
562+
{
563+
$hash_transient = 'form_tmpl_hash_' . $form_id;
564+
$template_hash = md5( $template );
565+
$stored_hash = get_transient( $hash_transient );
566+
567+
if ( ! $force && $template_hash === $stored_hash ) {
568+
return;
569+
}
570+
571+
// Safe-guard to prevent accidental infinite loops.
572+
remove_action( 'save_post', array( $this, 'save_cpt' ) );
573+
574+
$updated = wp_update_post( array(
575+
'ID' => (int) $form_id,
576+
'post_content' => $template
577+
) );
578+
579+
add_action( 'save_post', array( $this, 'save_cpt' ) );
580+
581+
// Maybe we should do something else than just silently fail if persisting failed above.
582+
if ($updated) {
583+
set_transient($hash_transient, $template_hash, HOUR_IN_SECONDS * 8);
584+
}
585+
}
586+
550587
/**
551588
* Handles saving our post meta
552589
*/

0 commit comments

Comments
 (0)