Obtain PostID From Within the wpcf7_before_send_mail CF7 Hook

August 2nd, 2015 - Posted by Steve Marks to PHP, Web Development.

We use the Contact Form 7 Plugin on pretty much every WordPress site we build that requires a form of some kind. On some occasions we’re required to hook into the sending of the form to do something prior to the actual email being sent out.

Fortunately the plugin comes with a handy hook called wpcf7_before_send_mail that we can use. Unfortunately however the global $post data isn’t available from within the hook in the event where the form is being submitted on a single post (or page).

The Solution

Although the global $post data, nor even just the post ID, isn’t accessible, we can get the information through a little bit of manipulation. I include the code below that will hook into wpcf7_before_send_mail and result in the post ID being extracted:

add_action("wpcf7_before_send_mail", "my_function");

function my_function($cf7)
{
    $submission = WPCF7_Submission::get_instance();

    if($submission) 
    {
        $unit_tag = $submission->get_meta( 'unit_tag' );
        $explode_unit_tag = explode("-", $unit_tag);

            // We're on the viewing request form
            $post_id = str_replace("p", "", $explode_unit_tag[2]);

            //... We now have the postID. Go forth and conquer
    }
}
Tags: ,
This entry was posted on Sunday, August 2nd, 2015 at 11:10 am by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first