Anyone working with Wordpress will be familiar with Contact Form 7, a wonderful piece of work that Takayuki Miyoshi keeps religiously up-to-date.
It struck me that one thing that would be useful if, like me, you make complex forms, is a visual preview. (possibly even a visual editor but let's not run before...)
Now, as I say it's a wonderful piece of work so 5 minutes hacking came up with this:
Adding this to the $panels array in edit-contact-form.php
'preview-panel' => array(
'title' => __( 'Preview', 'contact-form-7' ),
'callback' => 'wpcf7_editor_panel_preview' ),
makes a new tab, Preview.
Adding this to editor.php
function wpcf7_editor_panel_preview( $post ) {
$preview_code = $post->form_do_shortcode();
echo (do_shortcode($preview_code));
}
produces the goods.
Now there's a few things wrong with this which is where I need help (I'm way above my pay grade here)
I should be able to call the function that produce the shortcode directly rather than relying on the use of do_shortcode()
The submit button is active (not good) and the preview only works after the form is saved and the shortcode generated.
Can anyone help me with this?
If you look at admin/edit-contact-form.php
where $panels
is initialized, you'll see this line below that:
$panels = apply_filters( 'wpcf7_editor_panels', $panels );
You can inject your panel with this code in your theme or plugin:
add_filter( 'wpcf7_editor_panels', function($panels) {
$panels['preview-panel'] = array(
'title' => __( 'Preview', 'contact-form-7' ),
'callback' => 'wpcf7_editor_panel_preview'
);
return $panels;
}, 10, 1 ); // 10 = priority (default); 1 = nr of arguments
To disable the submit button, change your preview method slightly by wrapping it in a div with a custom class:
$preview_code = do_shortcode( $post->shortcode() );
echo "<div class='wpcf7-preview'>$preview_code</div>"
Now you can add some Javascript like this to disable the button:
$('.wpcf7-preview input[type="submit"]').attr('disabled', 'true')
There are quite a few shortcode tags declared, and to be as compatible as you can, it's best to rely on do_shortcode
. It appears that WPCF7 has it's own shortcode parsing functionality rather than using that of WP itself; another reason to leave it be. If you use do_shortcode
you can be relatively sure that the preview will match actual form rendered on the frontend.
I haven't found any functionality regarding drafts in the plugin, and there's no easy way to preview a form that's not been saved, since the code to render a form fetches data from the database. So your best bet is to extend your callback to save a copy of the form as a draft and render that:
$copy = $post->copy(); // see includes/contact-form.php
$copy->save(); // idem
echo "<div class='wpcf7-preview'>" . do_shortcode( $copy->shortcode() )
. "<script>$('.wpcf7-preview input[type="submit"]').attr('disabled', 'true')</script>"
. "</div>";
$copy->delete();