Fix for special mail tags when using form with php do_shortcode
-
I couldn’t find anyone else encountering this problem (although some threads about emails not working with special mail tags) but maybe people are and not posting about it or maybe someone will in future.
For Contact Form 7, with the shortcode for the form put in the content of a page or post, the special mail tags that can be used in the form’s fields that refer to properties of the post, such as [_post_author_email] (perhaps as the address to send the notification to), works fine. A very useful feature.
However, if you try to do the same thing php (as opposed to the page contents: perhaps you want to ensure that posts of a particular category always have a particular contact form on them that allow the visitor to email the author of the post) it doesn’t work but I’ve discovered how to make it work:
For example, if the shortcode for a form is:
[contact-form-7 id="123" title="Peculair Post Enquiry"]
Then the php to use that would be:
<?php echo do_shortcode('[contact-form-7 id="123" title="Peculair Post Enquiry"]'); ?>
But the results will be slightly different.
For the shortcode used directly in the posts content, the resultant html (view source of the page it produces), will include the following string in multiple places:
wpcf7-f123-p7890-o1
f123 is the ID of the form’s template (id=”123″ above)
p7890 is the ID of the post (a post with ID 2468 will have p2468)If you do the same in the the php version (echo do_shortcode) the p7890- is missing.
In php we can get the ID of the post so the fix is to do a find/replace in the results of do_shortcode before echoing it like this:
<?php echo str_replace('wpcf7-f123-o1', 'wpcf7-f123-p' . get_the_ID() . '-o1', do_shortcode('[contact-form-7 id="123" title="Peculair Post Enquiry"]')); ?>
Of course, replace 123 (all three instances) with the ID of the form.
Special mail tags that refer to the properties of the post (such as [_post_author_email]) will then work within the form.
Whether that’s a bug with Contact Form’s 7 shortcode or PHP’s do_shortcode, I have no idea but there it is and the fix is simple enough.
- The topic ‘Fix for special mail tags when using form with php do_shortcode’ is closed to new replies.