Skip to content

Instantly share code, notes, and snippets.

@JodiWarren
Created August 12, 2020 14:25
Show Gist options
  • Save JodiWarren/5abc2fb96288f138437262d5803fc203 to your computer and use it in GitHub Desktop.
Save JodiWarren/5abc2fb96288f138437262d5803fc203 to your computer and use it in GitHub Desktop.
Naively add autocomplete attribute to Contact Form 7 inputs
<?php
/**
* @param $content
*
* @return string|string[]
*/
function imp_wpcf7_form_elements( $content ) {
$valid_autocomplete = [
'name',
'email',
'url',
'country',
'country-name',
];
$matches = [];
preg_match('/name="([a-zA-Z]*)"/', $content, $matches);
// If there are no matches, just return
if (count($matches) < 1) {
return $content;
}
// If the attribute is not in the whitelist, return
if ( !in_array(strtolower($matches[1]), $valid_autocomplete) ) {
return $content;
}
// Find the position of it in the string again
$str_pos = strpos( $content, 'name="' . $matches[1] . '"' );
if ( $str_pos === false ) {
return $content;
}
return substr_replace( $content, ' autocomplete="' . strtolower($matches[1]) . '" ', $str_pos, 0 );
}
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment