Conditional Required Contact Form 7 Fields

Sometimes you may want to have a required field in Contact Form 7 only when another form field has a certain value. For example, if someone has an option to choose their preferred method of contact between email and telephone, you’d want to make the email address field or the phone call field required accordingly. This isn’t too difficult to accomplish in Contact Form 7. You can look at how Contact Form 7 validates text and email fields by viewing its code in:


Around line 91, you will see the validation filters defined by Contact Form 7:

add_filter( 'wpcf7_validate_text', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email', 'wpcf7_text_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'wpcf7_text_validation_filter', 10, 2 );

Then, you can look at the function that handles the validation, wpcf7_text_validation_filter. The function accepts two parameters – $result and $tag. The $tag is the field being validated and the $result is, well, the result of the validation. In other words, did something go wrong?

The user-entered text of the field being checked is assigned to $value. Then, the function checks the current tag type. Is it text? Email? And it will process it accordingly. If a value is empty but the field is required, for example, the result will be invalid:

$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

In this case the Contact Form 7 error message for required fields is given as an error (wpcf7_get_message( ‘invalid_required’ )). If $result-invalidate() is called, that field will fail validation and you will get a form error.

We’re not, of course, going to modify the plug-in’s files directly. We want to make our plug-in modifications safe from future plug-in updates so we will tie into the same filters that the plug-in uses. I can put this code in my theme’s functions.php file or put it into a my own plug-in. In my example, I am setting two conditional required fields – email and phone number. So, I will need to set my own custom validations for both text and email fields:

add_filter( 'wpcf7_validate_text', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_text*', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email', 'my_site_conditional_required', 10, 2 );
add_filter( 'wpcf7_validate_email*', 'my_site_conditional_required', 10, 2 );

For both the text (phone) and email fields, I am using the function, my_site_conditional_required, for my own custom validations. Here is my complete function:

function my_site_conditional_required($result, $tag) {
    $tag = new WPCF7_Shortcode( $tag );

    $name = $tag->name;

    $value = isset( $_POST[$name] )
        ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
        : '';

    if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

    if ( "email" == $name && 'Email' == $_POST['contact-method'] ) :
        if ( '' == $value ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
        elseif ( ! wpcf7_is_email( $value ) ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) );

    return $result;

Here is how it works. I am doing the same thing that Contact Form 7 does with setting the $value. Then, instead of checking the tag type, I want to check the tag name. I specifically want to look for the fields named “phone” or “email.” I also have a dropdown named “contact-form” so I can check the $_POST value of contact-form and use that to see if the field being checked should be required. If $_POST[‘contact-form’] is equal to “Phone,” I want the phone field to be required:

if ( "phone" == $name && 'Phone' == $_POST['contact-method'] ) :
        if ( '' == $value  ) :
            $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

I have an extra check for the email. I don’t just want to require the email address, I want to make sure it is a valid email address as well. Contact Form 7 provides a function to check an email, wpcf7_is_email:

elseif ( ! wpcf7_is_email( $value ) ) :

As you can see, my custom function works very similarly to the code in the plug-in. Finally, you probably want to show the user the field that is required based on their downdown selection. I added empty spans after the field labels that I can use to add and remove informational asterisks from:

<label class="email-label">Email<span class="asterisk"></span></label>

Then, I can use jQuery to add and remove the asterisks:

<script type="text/javascript">
 jQuery(function() {
 jQuery("select[name='contact-method']").on('change', function() {
 function add_required_asterisks() {
 if ( jQuery("select[name='contact-method']").val() == "Phone" ) {
 jQuery(".phone-label .asterisk").html("*");
 jQuery(".email-label .asterisk").html("");
 else {
 jQuery(".phone-label .asterisk").html("");
 jQuery(".email-label .asterisk").html("*");

I created a JavaScript function that will see what my dropdown menu (named “contact-method”) is set to and then, based on that, turn the asterisks on or off. Then, I call that function on page load and, whenever the dropdown changes:

jQuery("select[name='contact-method']").on('change', function() {

Quick WordPress Tip – Upload to a Post Without Switching Tabs

Here is a quick tip for WordPress users out there. When you are adding, say, a Featured Image to a post, you are brought to the Media Library window that includes an “Upload Files” tab. This might lead you to believe that you need to switch to that tab in order to upload a new image file. Actually, though, you can save yourself some clicks by simply dragging a photo onto the Media Library. No need to switch tabs.

Drop to Upload

Saving changes made in Chrome’s Web Inspector

It is wonderful to be able to use Chrome’s Web Inspector development tools to tweak the CSS of a web page to get elements just right. However, what is the best way to apply these changes to the actual stylesheet? One could, of course, just move these changes by recreating the tweaks to the CSS document manually. There is a way, though, to actually save out the modified CSS file right from the Web Inspector. To do this, simply click on the CSS link at the right-hand side of the Styles palette:

CSS link


Clicking on the link will open up the modified CSS file in the Web Inspector’s Sources tab:



Right-clicking on the opened CSS file will allow you to view the changes made to the CSS file via the Elements tool (Local Modifications) as well as save out the changed CSS file which you can use to replace the old CSS.

Right click

Using MailCatcher for local mail testing

When developing web applications on your local machine, you will often want to test e-mails. For the longest time, I would use an environmental switch in PHP depending on the domain (for example, I would set different values if the domain was stirrell.second-cup-of-coffee or and include values for email addresses. I had my local MAMP really sending out emails and this worked fine. Of course, there is always the chance you’re going to miss an email somewhere and inadvertently send out a real email when you just want to test.

A good solution to this problem is to use a “fake” SMTP server – a program that simulates sending an email and allows you to see what would have been sent – but only exists on your local machine. I had been using one on the Macintosh – MockSMTP which is available on the Mac App Store. It had been working fine for me. I set it up according to the instructions here and it all worked swimmingly… until I upgraded to the newest Mac OS X, Mavericks. I did not receive any errors but I also never received any test emails. Bummer. I sent a tweet to the folks who make MockSMTP but never got a response – the app itself has not been updated since 2011 so I fear that an update might not be coming.

I searched around for an alternative to MockSMTP. Many of the ones I saw were Java-based multi-platform solutions which did not appeal to me. I finally decided to give the free MailCatcher a try. MailCatcher is a Ruby Gem so is installed via the command line and called through the command line. I followed the instructions at their site and it worked straight away.

To get MailCatcher working with PHP, I edited the php.ini configuration files to use catchmail for the sendmail path. In MAMP, you simply go to File > Edit Template > PHP and then choose the version of PHP you are using. You can tell what version of PHP you are using with MAMP by going to the “Server” tab:

PHP version

I added the following line to my configuration file:

sendmail_path = /usr/bin/env catchmail

Once that is set, all email sent by PHP will go to MailCatcher. You can view mail sent to MailCatcher using a browser to connect to your local machine on port 1080 ( You will get a simple web interface for viewing the mails that have come in. From then on, simply type “mailcatcher” in the Terminal to start up MailCatcher. This will give you a simple way of testing emails on your local machine without worry of emails getting sent to the client.

Passing PHP variables to JavaScript

I was recently working on a project in CodeIgniter and I was setting numeric variables with constants for things like locations (1 = Maine, 2 = New Hampshire, etc.). This all worked fine but when it came to doing some JavaScript AJAX work I didn’t have access to these constants. One of the advantages to using these constants is that I did not want to have to change the value in more than one place if a value changed or I wanted to add a new location, for example. My way to solve this was to pass my PHP variables through to JavaScript using json_encode.

In my CodeIgniter controller, I set the variables I wanted to use in JavaScript:

$footerData['javascriptVariables'] = array(
'sheetID' => $sheetID

Then, in the footer, I checked for the existence of $javascriptVariables and, if it is not empty, I echoed out the json_encoded value:

// Were there any variables set via PHP for use in the JavaScript?
if (!empty($javascriptVariables)) {
echo "<script type='text/javascript'>\n";
echo "var php_variables = " . json_encode($javascriptVariables) . "\n";
echo "</script>\n";

This results in something like:

<script type='text/javascript'>
var php_variables = {"sheetID":"8"}

Then, in my JavaScript, I can easily get access to the sheetID set in PHP:


I suspect that I could also automate the process of making all my PHP constants available in JavaScript by using get_defined_constants.

Sublime Text’s Extend Selection to Word in TextMate 2

One of the coolest features of Sublime Text 2, in my opinion, is the ability to use the command, “Extend Selection to Word” with Sublime Text’s multiple cursors. Using this command, one can highlight a word they want to change, select the command (or the key command equivalent) which selects the next instance of the word with multiple cursors and then you can replace both words (or as many words as you select) by typing once. I thought that TextMate 2 was missing this feature and that I would have to replace words one at a time or rely on replacing all within a selection. It turns out, though, that TextMate has this feature as part of the Text Bundle.

By default, the “Extend Selection to Include Next” command is bound to the Control-w keys and is available in the Text bundle under Menu Actions > Selecting.

Extend Selection to Include Next

You can, of course, change the key binding (I made it the same as I have it in Sublime Text 2 – Command-D). I absolutely love this feature and am glad to see that it is available in TextMate 2.

Changing Posts per Page in WordPress admin

Here’s a quick WordPress tip. One thing that always bugged me about the admin interface is that WordPress shows just 20 posts per page in the admin list leading to a lot of clicking the paging navigation. Well, WordPress allows you to change the number of posts shown per page. Go to the Screen Options dropdown at the top of the page. One of the options is the number of posts. Change it to a larger number and deal less with clicking through pages. I never knew about this handy feature until a coworker of mine pointed it out.

Post per post WordPress

Display the caption of a featured image in WordPress

Have you ever wanted to display the caption of a Featured Image in WordPress? I recently had need to do this and figured out a way to accomplish this.

When you set the Featured Image for a post in WordPress, you can add additional information for the image: Title, Caption, Alt Text and Description.

Set caption for featured image

It makes sense to me that you might want to display the caption for a Featured Image, if entered. My solution to this was to add a function to my functions file to use to display the caption. My function looks like this:

 function my_display_featured_image( ) {
global $post;

$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_details = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
$thumbnail_src = wp_get_attachment_image_src( $thumbnail_id, 'full' );
$thumbnail_width = $thumbnail_src[1];

if ($thumbnail_src && isset($thumbnail_src[0])) {
echo '<div class="featured-image';
if ( !empty( $thumbnail_details[0]->post_excerpt ) ) echo ' wp-caption';
echo '" style="max-width: ' . $thumbnail_width . 'px;">';
if ( !empty( $thumbnail_details[0]->post_excerpt ) ) {
echo '<p class="featured-image-caption">';
echo $thumbnail_details[0]->post_excerpt;
echo '</p>';
the_post_thumbnail( $post->ID );
echo '</div>';

First, we get the information for the post we’re on. We do this by making the $post global. This will give us access to the id of the post we’re on. From there, we can call get_post_thumbnail_id to get the id of the Featured Image. Once we have the id of the Featured Image, or attachment, that we want, we can then use WordPress’s get_posts to grab the record of the Featured Image. The details of the Featured Image are stored in the variable $thumbnail_details using the call:

$thumbnail_details = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

get_posts accepts the arguments of WP_Query so, in our example, ‘p’ is the post id (the id of the Featured Image) which we were able to get using get_post_thumbnail_id. This query returns an object which includes the Featured Image’s caption in the ‘post_excerpt’ value and the description is available in the ‘post_content.’

I am also grabbing the source of the attachment image and using the width of the image to set some inline CSS (in my particular case I wanted to float the image so I wanted to set the width). wp_get_attachment_image_src gets the url and image dimensions and returns the values in an array.

So, now I have the image’s URL, dimensions and caption. With this information, we can display the image. To check if there is a caption present, I just need to check the value of the post_excerpt returned by my get_posts call.

if ( !empty( $thumbnail_details[0]->post_excerpt ) ) {
echo '<p class="featured-image-caption">';

Finally, I use the_post_thumbnail to display the featured image. In my template file, if the post has a Featured Image, I call my function to display the Featured Image.

<?php if ( has_post_thumbnail() ) :
endif; ?>

That is how I display a Featured Image’s caption.

Inspecting rollover elements in Chrome and Firefox

For some reason, this was never apparent to me but it is actually pretty straightforward. I used to use tricks to inspect rollover elements like changing the CSS display: none to display: block inline with Firebug. But there is actually a much easier way to test these elements.

In Chrome’s Web Inspector, simply use the Elements panel and click on the element, when hovered over, triggers a drop down menu. On the right-hand side of the Inspector, where the element’s CSS information is shown, there is an icon of a mouse pointer hovering over a dashed box. Click that, and you will be given options to change the state of the element. You can change the element’s state for active, hover, focus, and visited.

Changing the hover state in Chrome

In Firefox, using Firefox, doing this is just as easy. Inspect an element with Firebug and choose the item in the HTML panel. On the right-hand side, you will see the Style information for the selected element. The tab for the Style panel has a little down arrow to the right of the label. Click that and among the options are hover, active and focus. Click on hover and you can style the item that is hidden until triggered by a rollover.

Hover in Firebug

Again, this is probably something most people probably figured out long before I did but finding these features made my development much easier.