I'm attempting to call a Contact Form 7 form using AJAX in a Wordpress theme. I'd ideally like to use the Contact Form 7 shortcode to do this, however it doesn't seem as though do_shortcode is an available function when called using AJAX (it was just echoing out the shortcode itself).
I stumbled upon this question: Why might a plugin's 'do_shortcode' not work in an AJAX request?
which was exactly my problem! However the solution provided didn't work for me, and I'm pretty sure I implemented it the same way the original post did:
add_action( 'init', create_function('', 'register_shortcode_ajax( "cl_contact_us", "cl_contact_us" ); '));
function register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
function cl_contact_us() {
echo do_shortcode( '[contact-form-7 id="7" title="Contact form 1"]' );
die();
}
The only thing I had to change was how the anonymous function was being called from the add_action function (for some reason using a traditional anonymous function wasn't working, but using the PHP function works fine).
Aside from the above, the only thing that's radically different is the jQuery AJAX call, but I believe it's basically the same...
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
$(document).ready(function(){
$('a#contact-button').click(event, function() {
event.preventDefault();
$.post(
ajaxurl,
{
'action':'cl_contact_us',
},
function(response) {
$('#form').append(response);
});
});
});
This is successfully performing an AJAX call, but it's still just echoing out the shortcode, not the form.
I hope this is enough info, if you need any more I'll be here all day :) Any help is greatly appreciated. Thanks!