Skip to content

Instantly share code, notes, and snippets.

@huanyichuang
Last active December 21, 2018 00:53
Show Gist options
  • Save huanyichuang/6edca4880ea87ff40bc497e22a764ce4 to your computer and use it in GitHub Desktop.
Save huanyichuang/6edca4880ea87ff40bc497e22a764ce4 to your computer and use it in GitHub Desktop.
According to the original template file, I tried to create another tag that can integrate the TW address field in Contact Form 7.
<?php
add_action( 'wpcf7_init', 'wpcf7_add_address_tag' );
function wpcf7_add_address_tag () {
wp_enqueue_script( 'address-pick', get_template_directory_uri() . '/js/tw-city-selector/dist/tw-city-selector.min.js', array( 'jquery' ), true ) ;
//Get the js file from https://github.com/dennykuo/tw-city-selector
wpcf7_add_form_tag( array( 'address', 'address*' ),
//To-do: 還沒處理必填欄位的功能
'wpcf7_add_address_tag_handler', array( 'name-attr' => true ) );
}
function wpcf7_add_address_tag_handler ( $tag ) {
/**
* 以下根據 Contact Form 原始檔案照抄
*/
if ( empty( $tag->name ) ) {
return '';
}
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
$class .= ' wpcf7-validates-as-date'; //本來是用 date.php 改的,所以有這個 class,先不管
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
if ( $tag->has_option( 'readonly' ) ) {
$atts['readonly'] = 'readonly';
}
if ( $tag->is_required() ) {
$atts['aria-required'] = 'true';
}
$value = (string) reset( $tag->values );
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
if ( $tag->has_option( 'placeholder' ) || $tag->has_option( 'watermark' ) ) {
$atts['placeholder'] = $value;
$value = '';
}
var_dump ($tag);
$value = $tag -> get_default_option( $value );
$value = wpcf7_get_hangover( $tag->name, $value );
$atts['value'] = $value;
if ( wpcf7_support_html5() ) {
$atts['type'] = $tag->basetype;
} else {
$atts['type'] = 'text';
}
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
/**
* 照抄完畢,我還在研究各段的功能哈哈哈哈哈
*/
/**
* 前端呈現的樣子
*/
$html = sprintf(
'<div role="tw-city-selector" data-has-zipcode><input id="street" class="street" /></div><span class="wpcf7-form-control-wrap %1$s"><input id="address-string" %2$s hidden/>%3$s</span>',
sanitize_html_class( $tag->name ), $atts, $validation_error );
//用 jQuery 的方法,把地址選擇外掛的值回傳到真正的 input 元素內
add_action( 'wp_footer', function () { ?>
<script id="tw-selector">
new TwCitySelector();
(function($){
$("document").ready( function() {
$("#street").change(function() {
$("#address-string").val($( ".zipcode" ).val() + $(".county").val() + $(".district").val() + $(".street").val());
});
})})(jQuery);
</script>
<?php });
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment