Upload media in frontend

DOMJSPHP
<form class="uk-margin" action="" method="post">
  <div class="uk-margin" uk-form-custom style="width:100%;">
    <input type="file" class="btnUpload" id="user_brand_banner" accept="image/*" style="opacity: 0" />
    <button class="uk-position-relative uk-border-rounded link-opacity" style="background-color: #F3F1F3; width: 100%; height: 300px; border: 2px dashed #ccc;">
      <div class="uk-position-center uk-text-center text-height text-default"><i uk-icon="icon:cloud-upload;ratio:3"> </i><br>點擊上傳你的作者頁Banner</div>
      <div class="uk-background-cover uk-position-top-left" id="imgBannerPreview" data-src="<?php echo get_field('user_brand_banner','user_'.wp_get_current_user()->ID); ?>" uk-img style="width: 100%; height: 100%;"></div>
    </button>
    <p class="uk-margin-small-top uk-text-center">尺寸建議:1200 x 300px,檔案大小不得大於 300kb</p>
  </div>
</form>
var $ = jQuery.noConflict();
 
  $('.btnUpload').on('change', prepareUpload);

  function prepareUpload(event) { 
    var file = event.target.files;
    var id = $(this).attr('id');
    var security = $('#security').val();
    var data = new FormData();
    data.append("action", "upload_image");
    data.append("security", security);
    if( id === 'user_brand_banner'){
      $.each(file, function(key, value){
        data.append("user_brand_banner", value);
      })
    } else {
      $.each(file, function(key, value){
        data.append("user_brand_logo", value);
      })
    }

    $.ajax({
      url: '<?php echo admin_url("admin-ajax.php");  ?>',
      type: 'POST',
      data: data,
      cache: false,
      dataType: 'json',
      processData: false, // Don't process the files
      contentType: false, // Set content type to false as jQuery will tell the server its a query string request
      success: function(data, textStatus, jqXHR) {	
        if( data.response == "SUCCESS" ){
          var preview = "";
          if( data.type === "image/jpg" 
            || data.type === "image/png" 
            || data.type === "image/gif"
            || data.type === "image/jpeg"
          ) {
            if( id === 'user_brand_banner'){
              $('#imgBannerPreview').attr('data-src',data.url);
            } else {
              $('#imgLogoPreview').attr('data-src',data.url);
            }
          } else {
            preview = data.filename;
          }
        } else {
            alert( data.error );
        }
    }

    });

  }
add_action('wp_ajax_upload_image', 'upload_handle' );

function upload_handle() {

	$nonce = $_POST['security'];
  if (!wp_verify_nonce($nonce, 'ajax-upload-nonce')) { 
		wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求'));
	}

  $current_user = wp_get_current_user();
	$usingUploader = 2;
	$fileErrors = array(
		0 => "There is no error, the file uploaded with success",
		1 => "The uploaded file exceeds the upload_max_files in server settings",
		2 => "The uploaded file exceeds the MAX_FILE_SIZE from html form",
		3 => "The uploaded file uploaded only partially",
		4 => "No file was uploaded",
		6 => "Missing a temporary folder",
		7 => "Failed to write file to disk",
		8 => "A PHP extension stoped file to upload" );
	$posted_data =  isset( $_POST ) ? $_POST : array();
	$file_data = isset( $_FILES ) ? $_FILES : array();
	$data = array_merge( $posted_data, $file_data );
	$response = array();
	if( $usingUploader == 1 ) {
		if(isset($data['user_brand_banner'])){
			$uploaded_file = wp_handle_upload( $data['user_brand_banner'], array( 'test_form' => false ) );
		} else {
			$uploaded_file = wp_handle_upload( $data['user_brand_logo'], array( 'test_form' => false ) );
		}
		if( $uploaded_file && ! isset( $uploaded_file['error'] ) ) {
			$response['response'] = "SUCCESS";
			$response['filename'] = basename( $uploaded_file['url'] );
			$response['url'] = $uploaded_file['url'];
      $response['type'] = $uploaded_file['type'];
		} else {
			$response['response'] = "ERROR";
			$response['error'] = $uploaded_file['error'];
		}
	} elseif ( $usingUploader == 2) {
		if(isset($data['user_brand_banner'])){
			$attachment_id = media_handle_upload( 'user_brand_banner', 0 );
		} else {
			$attachment_id = media_handle_upload( 'user_brand_logo', 0 );
		}
		
		if ( is_wp_error( $attachment_id ) ) { 
			$response['response'] = "ERROR";
      $response['error'] = $fileErrors[ $data['user_brand_banner']['error'] ];
		} else {
			$fullsize_path = get_attached_file( $attachment_id );
			$pathinfo = pathinfo( $fullsize_path );
			$url = wp_get_attachment_url( $attachment_id );
			$response['response'] = "SUCCESS";
			$response['filename'] = $pathinfo['filename'];
			$response['url'] = $url;
			if(isset($data['user_brand_banner'])){
				update_field( 'user_brand_banner',$url,'user_'.wp_get_current_user()->ID );
			} else {
				update_field( 'user_brand_logo',$url,'user_'.wp_get_current_user()->ID );
			}
			$type = $pathinfo['extension'];
			if( $type == "jpeg"
			|| $type == "jpg"
			|| $type == "png"
			|| $type == "gif" ) {
				$type = "image/" . $type;
			}
			$response['type'] = $type;
		}
	}
	echo json_encode( $response );
	die();
}

Tags:

Login/Sign up Form ajax

// Login
form.height-form.uk-flex.uk-flex-middle.uk-padding-s.uk-padding-medium.uk-background-default.uk-box-shadow-medium(action='' method='post' style="border-radius: 20px; border: 1px solid #19233C")
  .uk-width-1-1
    h3.uk-text-center.text-large.uk-text-primary.uk-margin-medium-bottom.text-small-spacing 
      img.uk-margin-small-right.uk-position-relative(src='img/icon-user-circle.svg' style='top: 8px; width: 30px;') 
      span.text-medium-weight 會員登入
    .uk-margin-top
      input.uk-input.input-outline.uk-border-rounded#username(type='text' placeholder='輸入使用者名稱 or Email')
    .uk-margin-small-top
      input.uk-input.input-outline.uk-border-rounded#password(type='password' placeholder='密碼')
    p.uk-text-right.uk-margin-small-top
      a.text-xsmall.link-primary(href='#') 忘記密碼?
    .uk-margin-small-top
      a.uk-padding-remove.uk-width-1-1.uk-button.uk-button-primary.uk-border-rounded.text-white.uk-margin-small-bottom#btnLogin 登入
      a.uk-padding-remove.uk-width-1-1.uk-button.button-outline.uk-border-rounded.uk-text-primary 還沒有帳號?點我註冊
    .uk-margin-medium-top
      p.text-xsmall.uk-text-center.uk-margin-small-bottom.uk-heading-line
        span 或使用社群帳號登入
      a.uk-position-relative.uk-padding-remove.uk-width-1-1.uk-button.uk-button-primary.uk-border-rounded.text-white.uk-margin-small-bottom.link-opacity(style='background-color: #1877f2;')
        i.uk-position-center-left.uk-position-small(uk-icon='facebook')
        | Facebook 登入
      a.uk-position-relative.uk-padding-remove.uk-width-1-1.uk-button.uk-button-secondary.uk-border-rounded.text-white.uk-margin-small-bottom.link-opacity(style='background-color: #ea4235')
        i.uk-position-center-left.uk-position-small(uk-icon='google')
        | Google 登入
        
// Sign Up
form.height-form-register.uk-flex.uk-flex-middle.uk-padding-s.uk-padding-medium.uk-background-default.uk-box-shadow-medium(action='' method='post' style="border-radius: 20px; border: 1px solid #19233C")
  .uk-width-1-1
    h3.uk-text-center.text-large.uk-text-primary.uk-margin-medium-bottom.text-small-spacing 
      img.uk-margin-small-right.uk-position-relative(src='img/icon-user-circle.svg' style='top: 8px; width: 30px;') 
      span.text-medium-weight 免費申請
    .uk-margin-top
      input.uk-input.input-outline.uk-border-rounded.text-small(type='text' placeholder='使用者名稱')
    .uk-margin-small-top
      input.uk-input.input-outline.uk-border-rounded.text-small(type='email' placeholder='Email')
    .uk-margin-small-top
      input.uk-input.input-outline.uk-border-rounded.text-small(type='text' placeholder='手機號碼')
    .uk-margin-small-top
      input.uk-input.input-outline.uk-border-rounded.text-small(type='password' placeholder='密碼')
    .uk-margin-small-top
      input.uk-input.input-outline.uk-border-rounded.text-small(type='password' placeholder='確認密碼')
    p.uk-text-right.uk-margin-small-top
      a.text-xsmall.link-primary(href='#') 已經有帳號了?點我登入
    .uk-margin-small-top
      a.uk-padding-remove.uk-width-1-1.uk-button.uk-button-primary.uk-border-rounded.text-white.uk-margin-small-bottom#btnRegister 立即註冊
    .uk-margin-medium-top
      p.text-xsmall.uk-text-center.uk-margin-small-bottom.uk-heading-line
        span 或使用社群帳號註冊
      a.uk-position-relative.uk-padding-remove.uk-width-1-1.uk-button.uk-button-primary.uk-border-rounded.text-white.uk-margin-small-bottom.link-opacity(style='background-color: #1877f2;')
        i.uk-position-center-left.uk-position-small(uk-icon='facebook')
        | Facebook 註冊
      a.uk-position-relative.uk-padding-remove.uk-width-1-1.uk-button.uk-button-secondary.uk-border-rounded.text-white.uk-margin-small-bottom.link-opacity(style='background-color: #ea4235')
        i.uk-position-center-left.uk-position-small(uk-icon='google')
        | Google 註冊

// reset password
form.uk-margin-medium-top(action="<?php echo home_url(); ?>/wp-login.php?action=lostpassword" method="post")
  .uk-margin.uk-position-relative
    input.uk-input.uk-padding-small.uk-text-small(type="email" placeholder="電子郵件" required name="user_login")
    img.uk-position-small.uk-position-center-right(src="<?php echo get_template_directory_uri(); ?>/assets/img/icon-mail2.svg" uk-svg="" style="opacity: .9;")
  .uk-margin
    button.uk-button.uk-button-primary.uk-button-large.uk-width-1-1.text-small-spacing.text-white(type="submit" style="padding-left: 40px;") 索取新密碼
 // Login
<form class="ajax-auth height-form uk-flex uk-flex-middle uk-padding-s uk-padding-medium uk-background-default uk-box-shadow-medium" style="border-radius: 20px; border: 1px solid #19233C" action="login" method="post" id="login">
  <div class="uk-width-1-1">
    <h3 class="uk-text-center text-large uk-text-primary uk-margin-medium-bottom text-small-spacing"> <img class="uk-margin-small-right uk-position-relative" src="<?php echo get_template_directory_uri(); ?>/assets/img/icon-user-circle.svg" style="top: 8px; width: 30px;"><span class="text-medium-weight">會員登入</span></h3>
    <p id="messageLoginError" class="uk-background-secondary uk-padding-small uk-text-center uk-border-rounded text-small text-white" style="display:none;"></p>
    <div class="uk-margin-top">
      <input class="uk-input input-outline uk-border-rounded text-small" type="text" name="username" id="username" required placeholder="輸入使用者名稱 or Email" maxlength=50>
    </div>
    <div class="uk-margin-small-top">
      <input class="uk-input input-outline uk-border-rounded  text-small" type="password" id="password" name="password" required placeholder="密碼" maxlength=50>
    </div>
    <p class="uk-text-right uk-margin-small-top"><a class="text-xsmall link-primary" href="<?php echo home_url(); ?>/reset">忘記密碼?</a></p>
    <div class="uk-margin-small-top"><button type='submit' class="uk-padding-remove uk-width-1-1 uk-button uk-button-primary uk-border-rounded text-white uk-margin-small-bottom" id="btnLogin">登入</button><a href="<?php echo home_url(); ?>/register" class="uk-padding-remove uk-width-1-1 uk-button button-outline uk-border-rounded uk-text-primary">還沒有帳號?點我註冊</a></div>
    <div class="uk-margin-medium-top">
      <p class="text-xsmall uk-text-center uk-margin-small-bottom uk-heading-line"><span>或使用社群帳號登入</span></p><a class="uk-position-relative uk-padding-remove uk-width-1-1 uk-button uk-button-primary uk-border-rounded text-white uk-margin-small-bottom link-opacity" style="background-color: #1877f2;" alt="Login with Facebook" title="Login with Facebook" onclick="theChampInitiateLogin(this)"><i class="uk-position-center-left uk-position-small" uk-icon="facebook"></i>Facebook 登入</a>
      <!-- <a alt="Login with Google" title="Login with Google" onclick="theChampInitiateLogin(this)" class="uk-position-relative uk-padding-remove uk-width-1-1 uk-button uk-button-secondary uk-border-rounded text-white uk-margin-small-bottom link-opacity" style="background-color: #ea4235"><i class="uk-position-center-left uk-position-small" uk-icon="google"></i>Google 登入</a> -->
    </div>
  </div>
  <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
  
// Sign Up
<form class="ajax-auth height-form-register uk-flex uk-flex-middle uk-padding-s uk-padding-medium uk-background-default uk-box-shadow-medium" action="register" method="post" id="register" style="border-radius: 20px; border: 1px solid #19233C">
  <div class="uk-width-1-1">
    <h3 class="uk-text-center text-large uk-text-primary uk-margin-medium-bottom text-small-spacing"> <img class="uk-margin-small-right uk-position-relative" src="<?php echo get_template_directory_uri(); ?>/assets/img/icon-gift-circle.svg" style="top: 8px; width: 30px;"><span class="text-medium-weight">免費申請</span></h3>
    <p id="messageSignupError" class="uk-background-secondary uk-padding-small uk-text-center uk-border-rounded text-small text-white" style="display:none;"></p>
    <div class="uk-margin-top">
      <input class="uk-input input-outline uk-border-rounded text-small" type="text" pattern="[A-Za-z0-9]{1,}" title="請輸入英文或阿拉伯數字" placeholder="使用者名稱,限英數" id="signonname" name="signonname" required maxlength=50>
    </div>
    <div class="uk-margin-small-top">
      <input class="uk-input input-outline uk-border-rounded text-small" type="email" placeholder="Email" id="email" name="email" required>
    </div>
    <div class="uk-margin-small-top">
      <input class="uk-input input-outline uk-border-rounded text-small phone-format" type="text" placeholder="手機號碼" id="phone" name="phone">
    </div>
    <div class="uk-margin-small-top">
      <input class="uk-input input-outline uk-border-rounded text-small" type="password" placeholder="密碼" id="signonpassword" name="signonpassword" required maxlength=50 minlength=5>
    </div>
    <div class="uk-margin-small-top">
      <input class="uk-input input-outline uk-border-rounded text-small" type="password" placeholder="確認密碼" id="password2" name="password2" oninput="check(this)" required maxlength=50>
    </div>
    <p class="uk-text-right uk-margin-small-top"><a class="text-xsmall link-primary" href="<?php echo home_url(); ?>/login">已經有帳號了?點我登入</a></p>
    <div class="uk-margin-small-top"><button type="submit" class="uk-padding-remove uk-width-1-1 uk-button uk-button-primary uk-border-rounded text-white uk-margin-small-bottom" id="btnRegister">立即註冊</button></div>
    <div class="uk-margin-medium-top">
      <p class="text-xsmall uk-text-center uk-margin-small-bottom uk-heading-line"><span>或使用社群帳號登入</span></p><a class="uk-position-relative uk-padding-remove uk-width-1-1 uk-button uk-button-primary uk-border-rounded text-white uk-margin-small-bottom link-opacity" style="background-color: #1877f2;" alt="Login with Facebook" title="Login with Facebook" onclick="theChampInitiateLogin(this)"><i class="uk-position-center-left uk-position-small" uk-icon="facebook"></i>Facebook 登入</a>
      <!-- <a alt="Login with Google" title="Login with Google" onclick="theChampInitiateLogin(this)" class="uk-position-relative uk-padding-remove uk-width-1-1 uk-button uk-button-secondary uk-border-rounded text-white uk-margin-small-bottom link-opacity" style="background-color: #ea4235"><i class="uk-position-center-left uk-position-small" uk-icon="google"></i>Google 登入</a> -->
    </div>
  </div>
  <?php wp_nonce_field('ajax-register-nonce', 'signonsecurity'); ?>
</form>

// reset password
<form class="uk-margin-medium-top" action="<?php echo home_url(); ?>/wp-login.php?action=lostpassword" method="post">
  <div class="uk-margin uk-position-relative"><input class="uk-input uk-padding-small uk-text-small" type="email"
    placeholder="電子郵件" required name="user_login"><img class="uk-position-small uk-position-center-right"
    src="<?php echo get_template_directory_uri(); ?>/assets/img/icon-mail2.svg" uk-svg="" style="opacity: .9;"></div>
  <div class="uk-margin"><button
    class="uk-button uk-button-primary uk-button-large uk-width-1-1 text-small-spacing text-white"
    type="submit" style="padding-left: 40px;">索取新密碼 </button></div>
</form>
function check(input) {
  if (input.value != document.getElementById("signonpassword").value) {
    input.setCustomValidity("密碼必須符合!");
  } else {
    input.setCustomValidity("");
  }
}

jQuery(document).ready(function ($) {

  var redirectURL = window.location.href;
  
  $(".phone-format").keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
      return false;
    }
    var curchr = this.value.length;
    var curval = $(this).val();
    if (curchr == 4) {
      $(this).val(curval + "-");
    } else if (curchr == 8) {
      $(this).val(curval + "-");
    } else if (curchr == 12) {
      $(this).attr('maxlength', '12');
    }
  });

	$('form#login, form#register').on('submit', function (e) {
    e.preventDefault();
		ctrl = $(this);
		$('.uk-alert').fadeOut();
		$('#btnLogin').text('登入中...');
		$('#btnRegister').text('註冊中...');
		
    if ($(this).attr('id') == 'register') {
      document.getElementById('messageSignupError').style.display = "none";
      action = 'ajaxregister';
      username = $('#signonname').val();
      password = $('#signonpassword').val();
      phone = $('#phone').val();
      email = $('#email').val();
      security = $('#signonsecurity').val();
      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_auth_object.ajaxurl,
        data: {
          'action': action,
          'username': username,
          'password': password,
          'email': email,
          'phone': phone,
          'security': security
        },
        success: function (data) {
          if (data.loggedin == true) {
            document.location.href = redirectURL;
            $("#btnLogin").text("轉頁中...");
          } else {
            ctrl.prev().fadeIn("fast");
            document.getElementById('messageSignupError').textContent = data.message;
            document.getElementById('messageSignupError').style.display = "block";
            $("#btnRegister").text("立即註冊");
          }
        }
      });
    } else {
      action = 'ajaxlogin';
      username = $('form#login #username').val();
      password = $('form#login #password').val();
      security = $('form#login #security').val();
      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajax_auth_object.ajaxurl,
        data: {
          'action': action,
          'username': username,
          'password': password,
          'security': security
        },
        success: function (data) {
          if (data.loggedin == true) {
            document.location.href = redirectURL;
            $("#btnLogin").text("轉頁中...");
          } else {
            ctrl.prev().fadeIn("fast");
            document.getElementById('messageLoginError').textContent = data.message;
            document.getElementById('messageLoginError').style.display = "block";
            $("#btnLogin").text("登入");
          }
        }
      });
    }
	});
});
<?php

function ajax_auth_init(){ 

    wp_register_script('ajax-auth-script', get_template_directory_uri() . '/assets/js/ajax-login.js', array('jquery'), null,true ); 
    wp_enqueue_script('ajax-auth-script');

    wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array( 
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => wp_get_referer(),
        'loadingmessage' => __('登入中...')
    ));

    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
    // Enable the user with no privileges to run ajax_register() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxregister', 'ajax_register' );

}

// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'ajax_auth_init');
}
  
function ajax_login(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-login-nonce', 'security' );

    // Nonce is checked, get the POST data and sign user on
    // Call auth_user_login
    auth_user_login($_POST['username'], $_POST['password'], '登入成功!'); 
    
    die();
}

function ajax_register(){

    // First check the nonce, if it fails the function will break
    check_ajax_referer( 'ajax-register-nonce', 'security' );
        
    // Nonce is checked, get the POST data and sign user on
    $info = array();
    $info['user_nicename'] = $info['first_name'] = $info['user_login'] = sanitize_user($_POST['username']) ;
    $info['nickname'] = $info['display_name'] = sanitize_text_field($_POST['nickname']) ;
    $info['user_pass'] = sanitize_text_field($_POST['password']);
    $info['user_email'] = sanitize_email( $_POST['email']);
    
    // Register the user
    $user_register = wp_insert_user( $info );
    if ( is_wp_error($user_register) ){ 
        $error  = $user_register->get_error_codes() ;
        if(in_array('empty_user_login', $error))
            echo json_encode(array('loggedin'=>false, 'message'=>__($user_register->get_error_message('empty_user_login'))));
        elseif(in_array('existing_user_login',$error))
            echo json_encode(array('loggedin'=>false, 'message'=>__('該帳號已被註冊')));
        elseif(in_array('existing_user_email',$error))
        echo json_encode(array('loggedin'=>false, 'message'=>__('該郵件已被註冊')));
    } else {
        $headers = 'From:  Sender<service@mail.com>' . "rn";
        $message = '';
        auth_user_login($info['user_login'], $info['user_pass'], '註冊完成!');
        update_field('user_phone',$_POST['phone'],'user_'.$user_register);    
        update_field('user_status','paid','user_'.$user_register);    
    }

    die();
}

function auth_user_login($user_login, $password, $login){
    $info = array();
    $info['user_login'] = $user_login;
    $info['user_password'] = $password;
    $info['remember'] = true;
    
    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('帳密有誤!請重新輸入')));
    } else {
        wp_set_current_user($user_signon->ID); 
        echo json_encode(array('loggedin'=>true, 'message'=>__($login.' 轉址中...')));
    }
    
    die();
}

Tags:

Contact form with attachment and reCAPTCHA

The contact form sample with email attachment and Google reCAPTCHA. There are two ways to avoid bots. First, it uses the empty hidden input, and PHP will check this input is empty when bots fill it automatically. After then, it uses the wp_create_nonce and wp_verify_nonce to check the form sending is come from this site.

Thumbnail

PHPJSPugSCSS
// <head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<?php
$fullname = (isset($_POST['fullname']))?sanitize_text_field($_POST['fullname']):'';
$nickname = (isset($_POST['nickname']))?sanitize_text_field($_POST['nickname']):'';
$lname = (isset($_POST['lname']))?sanitize_text_field($_POST['lname']):''; 	// honey pot
$phone = (isset($_POST['phone']))?sanitize_text_field($_POST['phone']):'';
$email = (isset($_POST['email']))?sanitize_email($_POST['email']):'';
$subject = (isset($_POST['subject']))?sanitize_text_field($_POST['subject']):'';
$message = (isset($_POST['message']))?sanitize_textarea_field($_POST['message']):'';
$attach = (isset($_FILES['attach']['name']))?$_FILES['attach']['name']:'';

if( isset( $_POST['contact_form'] ) && wp_verify_nonce( $_POST['contact_form'], 'send_form' )){		// use nonce to avoid CSRF
	$sendStauts;
	if( !empty($nickname) && !empty($subject) && !empty($message) && empty($lname) ){

		// Attachment have to upload to media first.
		$post_id = $post->ID;
		if ( !empty($_FILES)  ) {
			require_once( ABSPATH . 'wp-admin/includes/admin.php' );
			$id = media_handle_upload( 'attach', $post_id );
			unset( $_FILES );
			if( is_wp_error( $id ) ) {
				$errors['upload_error'] = $id;
				$id = false;
			}
    }

		$attachments = array( get_attached_file($id) );		// Get the attachment path
		$headers = 'Content-Type: text/html; charset=UTF-8';
		$content = '<div><p>來信主旨:'.$subject.'</p><p>姓名:'.$fullname.'</p><p>暱稱:'.$nickname.'</p><p>電話:'.$phone.'</p><p>電子郵件:'.$email.'</p><p>詢問內容:'.$message.'</p></div>';
		wp_mail( get_option('admin_email'),'【'.get_the_title().'】投稿通知信', $content,$headers,$attachments );
		$sendStauts = true;
	} else {
		$sendStauts = false;
	}
}
?>

<section class="uk-margin-medium-top">
	<div class="uk-container">
		<h1 class="uk-text-primary heading-small text-bold heading-underline uk-margin-medium-bottom" style="line-height:1;"><span><?php echo esc_html(get_the_title()); ?></span></h1>
		<div class="uk-width-2-3@m">
			<?php if(isset($sendStauts)): ?>
				<?php if($sendStauts): ?>
				<div class="uk-alert-success" uk-alert>
					<a class="uk-alert-close" uk-close></a>
					<p>投稿成功,感謝您的來信,我們會由專人協助您投稿!</p>
				</div>
				<?php else: ?>
					<div class="uk-alert-danger" uk-alert>
					<a class="uk-alert-close" uk-close></a>
					<p>投稿失敗,請確認欄位是否已填寫正確!</p>
				</div>
				<?php endif; ?>
			<?php endif; ?>
			<h2 class="text-medium uk-margin-medium-bottom uk-text-primary">請填寫以下資料<span class="text-red text-xsmall uk-margin-small-left">( * 請務必填寫完整)</span></h2>
			<form method="post" action="<?php echo esc_url(get_the_permalink()); ?>" enctype="multipart/form-data">
				<div class="uk-margin-medium-bottom uk-child-width-1-2@s" uk-grid>
					<div>
						<label class="text-medium uk-display-block uk-margin-small-bottom">&nbsp;姓名<span class="text-small text-gray">&nbsp;</span></label>
						<input class="uk-border-rounded uk-input background" name="fullname" type="text" style="height: 54px;" maxlength="20" placeholder="王小明" value="<?php echo esc_attr($fullname); ?>">
					</div>
					<div class="uk-hidden">
						<label class="text-medium uk-display-block uk-margin-small-bottom">&nbsp;姓名<span class="text-small text-gray">&nbsp;</span></label>
						<input class="uk-border-rounded uk-input background" name="lname" type="text" style="height: 54px;" maxlength="20" placeholder="王小明">
					</div>
					<div>
						<label class="text-medium uk-display-block uk-margin-small-bottom"><span class="text-red">*</span>&nbsp;暱稱</label>
						<input class="uk-border-rounded uk-input background" name="nickname" type="text" style="height: 54px;" maxlength="20" required placeholder="小明" value="<?php echo esc_attr($nickname); ?>">
					</div>
				</div>
				<div class="uk-margin-medium-bottom uk-child-width-1-2@s" uk-grid>
					<div>
						<label class="text-medium uk-display-block uk-margin-small-bottom">&nbsp;電話<span class="text-small text-gray">&nbsp;</span></label>
						<input class="uk-border-rounded uk-input background" name="phone" type="text" style="height: 54px;" maxlength="20" placeholder="0966-xxx-xxx" value="<?php echo esc_attr($phone); ?>">
					</div>
					<div>
						<label class="text-medium uk-display-block uk-margin-small-bottom">&nbsp; E-mail<span class="text-small text-gray">&nbsp;</span></label>
						<input class="uk-border-rounded uk-input background" name="email" type="email" style="height: 54px;" maxlength="100" placeholder="email@mail.com" value="<?php echo esc_attr($email); ?>">
					</div>
				</div>
				<div class="uk-margin-medium-bottom">
					<label class="text-medium uk-display-block uk-margin-small-bottom"><span class="text-red">*</span>&nbsp;信件主旨</label>
					<input class="uk-border-rounded uk-input background" name="subject" type="text" style="height: 54px;" maxlength="100" required value="<?php echo esc_attr($subject); ?>">
				</div>
				<div class="uk-margin-medium-bottom">
					<label class="text-medium uk-display-block uk-margin-small-bottom"><span class="text-red">*</span>&nbsp; 信件內容</label>
					<textarea class="uk-border-rounded uk-textarea background" name="message" rows="10" required></textarea>
				</div>
				<div class="uk-margin-large-bottom">
					<label class="text-medium uk-display-block uk-margin-small-bottom">&nbsp; 附加檔案(格式 : .jpg .png .txt .doc .xls,容量小於 20MB)</label>
					<div class="uk-margin">
						<div uk-form-custom="target: true">
							<input id="attach" type="file" accept=".jpg,.png,.txt,.doc,.xls" name="attach">
							<input class="uk-input uk-form-width-medium uk-border-rounded" type="text" placeholder="選擇檔案" disabled="" style="height: 54px;">
							<button class="uk-button uk-button-primary uk-border-rounded text-medium" style="height: 54px;">瀏覽</button>
						</div>
					</div>
				</div>
				<div class="uk-margin-auto-left uk-margin-auto-right uk-margin-large-bottom" style="width: 320px;">
					<!-- <reCAPTCHA>-->
					<div class="uk-margin-auto-left uk-margin-auto-right uk-margin-medium-bottom g-recaptcha" style="width: 304px" data-sitekey="6LeqxdgUAAAAAFOIpdA9lFLdownnGnfrMORxwW97"></div>
					<!-- </reCAPTCHA>-->
					<div class="uk-child-width-1-2 uk-grid-small" uk-grid>
						<div>
							<button class="uk-width-1-1 text-medium uk-button uk-button-default uk-border-rounded" type="reset" style="height: 54px;">重填</button>
						</div>
						<div>
							<button class="uk-width-1-1 text-medium uk-button uk-button-primary uk-border-rounded" type="submit" style="height: 54px;">送出</button>
						</div>
					</div>
				</div>
				<?php wp_nonce_field( 'send_form', 'contact_form' ); ?>
			</form>
		</div>
	</div>
</section>
// check the attachment file size
if (vars.attach !== null){
  vars.attach.addEventListener('change',e=>{
    if (e.currentTarget.files[0].size > 20971520){
      alert('附件容量不得超過 20MB');
      e.currentTarget.value =''
    }
  })
}
div(class='uk-width-2-3@m')
  h2.text-medium.uk-margin-medium-bottom.uk-text-primary
    | 請填寫以下資料
    span.text-red.text-xsmall.uk-margin-small-left ( * 請務必填寫完整)
  form(method='post' action='/')
    .uk-margin-medium-bottom(uk-grid class='uk-child-width-1-2@s')
      div
        label.text-medium.uk-display-block.uk-margin-small-bottom
          | &nbsp;姓名
          span.text-small.text-gray &nbsp;(不會公開)
        input.uk-border-rounded.uk-input.background(name='lastname' type='text' style='height: 54px;' max='20' placeholder='王小明')
      div
        label.text-medium.uk-display-block.uk-margin-small-bottom
          span.text-red *
          | &nbsp;暱稱
        input.uk-border-rounded.uk-input.background(name='nickname' type='text' style='height: 54px;' max='20' required placeholder='小明')
    .uk-margin-medium-bottom(uk-grid class='uk-child-width-1-2@s')
      div
        label.text-medium.uk-display-block.uk-margin-small-bottom
          | &nbsp;電話
          span.text-small.text-gray &nbsp;(不會公開)
        input.uk-border-rounded.uk-input.background(name='phone' type='text' style='height: 54px;' max='20' placeholder='0966-xxx-xxx')
      div
        label.text-medium.uk-display-block.uk-margin-small-bottom
          | &nbsp; E-mail
          span.text-small.text-gray &nbsp;(不會公開)
        input.uk-border-rounded.uk-input.background(name='email' type='email' style='height: 54px;' max='100' placeholder='mail@msil.com')
    .uk-margin-medium-bottom
      label.text-medium.uk-display-block.uk-margin-small-bottom
        span.text-red *
        | &nbsp;信件主旨
      input.uk-border-rounded.uk-input.background(name='subject' type='text' style='height: 54px;' max='100' required)
    .uk-margin-medium-bottom
      label.text-medium.uk-display-block.uk-margin-small-bottom
        span.text-red *
        | &nbsp; 信件內容
      textarea.uk-border-rounded.uk-textarea.background(name='message' rows='10' required)
    .uk-margin-large-bottom
      label.text-medium.uk-display-block.uk-margin-small-bottom
        | &nbsp; 附加檔案(格式 : .jpg .png .txt .doc .xls,容量小於 20MB)
      .uk-margin
        div(uk-form-custom="target: true")
          input#attach(type="file" accept=".jpg,.png,.txt,.doc,.xls" name='attach')
          input.uk-input.uk-form-width-medium.uk-border-rounded(type="text" placeholder="選擇檔案" disabled="" style='height: 54px;')
          button.uk-button.uk-button-primary.uk-border-rounded.text-medium(style='height: 54px;') 瀏覽
    .uk-margin-auto-left.uk-margin-auto-right.uk-margin-large-bottom(style='width: 320px;')
      // <reCAPTCHA>
      .uk-margin-auto-left.uk-margin-auto-right.uk-margin-medium-bottom(style='width: 304px' class="g-recaptcha" data-sitekey="6LeqxdgUAAAAAFOIpdA9lFLdownnGnfrMORxwW97")
      // </reCAPTCHA>
      .uk-child-width-1-2.uk-grid-small(uk-grid)
        div
          button.uk-width-1-1.text-medium.uk-button.uk-button-default.uk-border-rounded(type='reset' style='height: 54px;') 重填
        div
          button.uk-width-1-1.text-medium.uk-button.uk-button-primary.uk-border-rounded(type='submit' style='height: 54px;') 送出
.uk-input,
.uk-textarea {
  &.background {
    padding-left: 15px;
    background-color: #f5f6f6;
    &:focus {
      border: 1px solid $global-primary-background;
      background-color: #fff;
    }
  }
}

Search form border-left only

The search input with border-left and submit icon only.

Thumbnail

PugSCSS
form.uk-position-relative(method='get' action="" style='height: 42px;')
  input.uk-input.text-small.input-keyword(type='text' max='100' name='s' placeholder='輸入關鍵字...' style='padding:0 0 0 15px')
  span.uk-position-center-left
  button.uk-position-center-right(type='submit')
    img(src='img/icon-search_orange.svg' uk-svg)
    img(src='img/icon-search_orange.svg')
.input-keyword {
  & + span {
    width: 1px;
    height: 20px;
    display: block;
    background-color: #efefef;
  }
  & + span + button img:first-child + svg {
      display: block;
    }
  & + span + button img:last-child {
    display: none;
  }
  &:focus {
    background-color: #efefef;
    & + span {
      background-color: #707070;
    }
    & + span + button img:first-child + svg {
      display: none;
    }
    & + span + button img:last-child {
      display: block;
    }
  }
}

Tags: