Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active June 8, 2018 01:59
Show Gist options
  • Save morgyface/38f47d64f9d5838efbc96f67d3f0fb47 to your computer and use it in GitHub Desktop.
Save morgyface/38f47d64f9d5838efbc96f67d3f0fb47 to your computer and use it in GitHub Desktop.
WordPress | Contact Form 7 | Display any forms that match the page title
<?php
// If there is a CF7 form with the same name as the current page let us display it.
$current_page_title = get_the_title();
$cf7form = get_page_by_title( $current_page_title, OBJECT, 'wpcf7_contact_form' );
if ( $cf7form ) {
$formid = $cf7form->ID;
$formtitle = $cf7form->post_title;
echo( do_shortcode('[contact-form-7 id="' . $formid . '" title="' . $formtitle . '"]') );
}
?>
@morgyface
Copy link
Author

morgyface commented Jul 1, 2016

Simply give your CF7 form the same name as the page/post you want it to appear on

Surprisingly I use this a lot. Even though it's not particularly complicated to post the short-code into the content of a post/page novice users may struggle. It's also not that transportable and sometimes you want to surround the form with additional html or position it in a specific place on the page outside of the main content.

This is a good solution in that it simply looks for a CF7 form, using get_page_by_title, with the same name as the current page and then echos the shortcode if it exists.

@morgyface
Copy link
Author

Note. This Gist was updated in February 2017. I previously used get_posts but realised it was unnecessary and overly bulky.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment