커스텀 애트리뷰트를 추가하는 방법
javascript 없이 Contact Form 7 필드에 커스텀 속성을 추가하려면 어떻게 해야 합니까?
예를 들어 페이지에는 다음과 같은 필드가 있습니다.
<input type="text" name="name" class="form-control" id="name-1" data-attr="custom" data-msg="Текст 1">
질문: 이러한 커스텀 속성을 설정할 수 있습니까?data-attr
,data-msg
관리 패널의 필드)를 선택합니다.
필드의 이름을 찾습니다.
[text* text-21]
필드 이름="text-21"의 이름이 제 예와 같이 있으면 이 코드를 함수에 추가합니다.php 파일.
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="text-21"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
이름이 text-21인 모든 폼 요소에 이러한 속성이 추가되므로 이를 방지하려면 폼 요소에 원하는 이름을 지정합니다.
그리고 코드를 로 변경합니다.
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="unique-name"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
다음은 필드 이름과 속성을 하드 코딩하지 않는 일반적인 솔루션입니다.
add_filter( 'wpcf7_form_tag', function ( $tag ) {
$datas = [];
foreach ( (array)$tag['options'] as $option ) {
if ( strpos( $option, 'data-' ) === 0 ) {
$option = explode( ':', $option, 2 );
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if ( ! empty( $datas ) ) {
$id = uniqid('tmp-wpcf');
$tag['options'][] = "class:$id";
add_filter( 'wpcf7_form_elements', function ($content) use ($id, $datas) {
return str_replace($id, $name, str_replace($id.'"', '"'. wpcf7_format_atts($datas), $content));
});
}
return $tag;
} );
모든 데이터 속성에서 작동하므로 다음과 같이 사용할 수 있습니다.
[text* my-name data-foo:bar data-biz:baz placeholder "Blabla"]
Output: <input type="text" name="my-name" data-foo="bar" data-biz="baz" placeholder="Blabla">
wpcf7은 옵션에 직접 접속하는 방법을 제공하지 않기 때문에 솔루션은 트릭을 사용하여 고유하게 생성된 클래스를 필드에 추가하며 나중에 추가된 속성으로 대체됩니다.
데이터 속성뿐만 아니라 다른 속성으로도 작업해야 하는 경우 이 행을 바꾸면 몇 가지 속성을 화이트리스트에 추가할 수 있습니다.
if ( strpos( $option, 'data-' ) === 0 ) {
다음과 같은 것으로
if ( preg_match( '/^(data-|pattern|my-custom-attribute)/', $option ) ) {
주의:wpcf7_format_atts
빈 Atribute는 출력되지 않으므로 Atribute에 값을 지정합니다.
복수의 어트리뷰트를 추가할 수도 있습니다.예
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="your-email-homepage"' );
$content = substr_replace( $content, ' aria-describedby="emailHelp" ', $str_pos, 0 );
$str_pos2 = strpos( $content, 'name="your-fname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="fnameHelp" ', $str_pos2, 0 );
$str_pos3 = strpos( $content, 'name="your-lname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="lnameHelp" ', $str_pos3, 0 );
return $content;
}
Tofandel의 솔루션에서 확장하여 99%를 얻었지만 검증에 어려움을 겪고 있는 사람들의 이익을 위해 저는 그것을 해결했습니다.또한 Tofandel의 솔루션(속성을 적절한 형태로 변환)을 실현하는 확장 솔루션을 제공하고 싶습니다.
add_filter('wpcf7_form_tag', function($tag) {
$data = [];
foreach ((array)$tag['options'] as $option) {
if (strpos( $option, 'autocomplete') === 0) {
$option = explode(':', $option, 2);
$data[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if(!empty($data)) {
add_filter('wpcf7_form_elements', function ($content) use ($tag, $data) {
$data_attrs = wpcf7_format_atts($data);
$name = $tag['name'];
$content_plus_data_attrs = str_replace("name=\"$name\"", "name=\"$name\" " . $data_attrs, $content);
return $content_plus_data_attrs;
});
}
return $tag;
} );
태그 ID를 랜덤한 값으로 변경하여 나중에 "실제" 값으로 치환하는 것이 아니라 처음에 실제 값을 참조하고 wpcf7_form_elements 필터의 콘텐츠 관련 부분을 바꿉니다(이 경우 자동 완성이지만 Tofandel의 예에서 알 수 있듯이 이것은 원하는 데이터 속성으로 확장할 수 있습니다).
JS(CF7) 오류가 없는 Tofandel이 제공한 솔루션과 값이 없는 속성 사용을 승인하는 솔루션을 제안합니다.
/**
* Add custom attributes on inputs
* Put "data-my-attribute" to use it, with or without value
*
* @param array $tag
*
* @return array
*/
function cf7AddCustomAttributes($tag) {
$datas = [];
foreach ((array) $tag['options'] as $option) {
if (strpos($option, 'data-') === 0 || strpos($option, 'id:') === 0) {
$option = explode(':', $option, 2);
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if (!empty($datas)) {
$id = $tag['name'];
if (array_key_exists('id', $datas)) {
$id = $datas['id'];
} else {
$tag['options'][] = "id:$id";
}
add_filter('wpcf7_form_elements', function ($content) use ($id, $datas) {
$attributesHtml = '';
$idHtml = "id=\"$id\"";
foreach ($datas as $key => $value) {
$attributesHtml .= " $key";
if (is_string($value) && strlen($value) > 0) {
$attributesHtml .= "=\"$value\"";
}
}
return str_replace($idHtml, "$idHtml $attributesHtml ", $content);
});
}
return $tag;
}
add_filter('wpcf7_form_tag', 'cf7AddCustomAttributes');
속성 설정에 이 간단한 방법을 사용합니다.
[checkbox optName use_label_element "optName"]
<script>
document.querySelector(".optName").setAttribute("onchange","myscript");
</script>
언급URL : https://stackoverflow.com/questions/46274317/how-to-add-a-custom-attribute
'programing' 카테고리의 다른 글
MongoDB에서 데이터베이스 간에 컬렉션을 복사하는 방법 (0) | 2023.03.20 |
---|---|
바인드 클래스를 창 스크롤 이벤트로 전환 (0) | 2023.03.20 |
JSON 오브젝트에 후행 콤마를 사용할 수 있습니까? (0) | 2023.03.20 |
모든 eslint 규칙에 오류가 아닌 경고를 표시할 수 있습니까? (0) | 2023.03.20 |
각도 부트스트랩모달:알 수 없는 공급자: $modal인스턴스 프로바이더 (0) | 2023.03.20 |