How can I remove the span wrapper in Contact Form 7? How can I remove the span wrapper in Contact Form 7? wordpress wordpress

How can I remove the span wrapper in Contact Form 7?


I faced the same problem and finally ending by using the wpcf7_form_elements filter to remove the <span> tag with a regex. You can for example copy-paste this code in your functions.phpfile. Here I pass an an anonymous function as a callback, so be sure to have PHP >= 5.3.

add_filter('wpcf7_form_elements', function($content) {    $content = preg_replace('/<(span).*?class="\s*(?:.*\s)?wpcf7-form-control-wrap(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $content);    return $content;});


I tried similar stuff the other day and many people mentioned, that Regex is not the proper way to alter HTML/remove tags etc and it sounds logic.

So i went for DOMDocument and came up with following solution:

add_filter('wpcf7_form_elements', function( $content ) {  $dom = new DOMDocument();  $dom->preserveWhiteSpace = false;  $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);  $xpath = new DomXPath($dom);  $spans = $xpath->query("//span[contains(@class, 'wpcf7-form-control-wrap')]" );  foreach ( $spans as $span ) :    $children = $span->firstChild;    $span->parentNode->replaceChild( $children, $span );  endforeach;  return $dom->saveHTML();});

EDIT:I now also added some html/text to my form, and the first heading element was not wrapping correctly after i used the DOMDocument class. It started in the first line and ended at the very end of the form. so i wrapped my entire form in a div, what made the markup return properly again.


You can remove the span wrapper using jQuery:

$("#name").unwrap();

It will remove input's parent element, so in this case it will remove the span.Please note that after removing the span, some Contact Form 7 features may not work correctly. For example validation may not work.

$("button").click(function(){  $("#name").unwrap();});
span {  background-color: #333;  padding: 20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span class="wpcf7-form-control-wrap name">  <input type="text" name="name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required form-control" id="name" aria-required="true" aria-invalid="false"></span><button>Remove span</button>