Retrieving data from a form created with Contact Form 7

If you want to get the data from a form created with Contact Form 7 you can use the ‘wpcf7_before_send_mail’ hook. In your functions.php or from your plugin add action like follows:

add_action( 'wpcf7_before_send_mail', 'my_plugin_wpcf7_before_send_mail' );

function my_plugin_wpcf7_before_send_mail ( $contact_form ) {
    // TODO: get the data
}

Since version 3.9 Contact Form 7 removed $contact_form->posted data so this hook might seem like it is no longer working.

However we can still get the data but using a bit different approach provided by the Contact Form 7 API

function my_plugin_wpcf7_before_send_mail ( $contact_form ) {
    $wpcf7_submission = WPCF7_Submission::get_instance();

    $posted_data = $wpcf7_submission->get_posted_data();

    // in $posted_data you have the things sent via the form
    // try $posted_data[ 'your-email' ] to get the email from a default contact form
}

Using the $posted_data retrieved in the shown way we can get any of the fields that were sent by the user using the created form.

[Tips and Tricks for Writing WordPress Themes and Plugins] Forcing the browser to refresh your scripts and styles

I’m starting a some kind of thread of posts where I write down some of the nice tricks I meet in WordPress development.

First one is how to write your custom theme and plugin files so after each deployment / update you’ll be sure that the browser doesn’t use the cached version of your JS and CSS.

This one is really easy – first you define a constant in your code for the version of your theme / plugin:

// You can either define it manually
if ( ! defined( 'MY_THEME_VERSION' ) ) {
    define( 'MY_THEME_VERSION', '0.0.1' );
}
// Or you can use the version from your style.css for the theme
$theme_data = wp_get_theme();
// $theme_data [ 'Version ' ] is the theme version

// Or your version from your plugin.php for plugin with:
$plugin_data = get_plugin_data( $plugin_file );
// $plugin_data[ 'Version' ] is the plugin version

Than the only thing you need to do is to add this version number to the scripts and styles you include (that are custom for the theme).

// For CSS
wp_enqueue_style( 'my_theme_css', get_stylesheet_directory_uri() . '/library/css/style.css', array(), MY_THEME_VERSION );
// For JS
wp_enqueue_script( 'my_theme_js', get_stylesheet_directory_uri() . '/library/js/script.js', array(), MY_THEME_VERSION );

And every time you deploy you can either manually increase the version number or you can use a build script to do it for you 😉

Cheers and follow me on twitter- @ninarski