Slim Select with WordPress.org API
Slim select is an excellent library for select field type. There are rich API to implement many features. Code below is a example of selecting the the WordPress themes from WordPress.org with its API. https://slimselectjs.com/options
Thumbnail

// js import SlimSelect from "slim-select"; /** * 佈景主題下拉選單 */ new SlimSelect({ select: '#selectTheme', searchingText: 'Searching...', searchText: 'No results, you can click right button to add new one if you want!', placeholder: 'Choose one', ajax: function (search, callback) { if (search.length < 3) { callback('Need 3 characters') return } // Perform your own ajax request here fetch('https://api.wordpress.org/themes/info/1.1/?action=query_themes&request[search]='+ search +'&request[per_page]=99') .then(function (response) { return response.json() }) .then(function (json) { let data = [] for (let i = 0; i < json.themes.length; i++) { data.push({ value: json.themes[i].slug, text: json.themes[i].name }) } callback(data) }) .catch(function (error) { callback(error) }) }, addable: function (value) { // return false or null if you do not want to allow value to be submitted if (value === 'fuck') { return false } // Return the value string return value // Optional - value alteration // ex: value.toLowerCase() } });
Tags:
- ajax
- /
- select
- /
- wordpress-org-api
- /
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:
- ajax
- /
Ajax framework
var $ = jQuery.noConflict() $(function(){ $('#btn').on('click',function(){ var data = { action: "myajax", // 這是綁定 wp hook 的關鍵字,千千萬萬不能漏掉 security: ajax_params.nonce, // toekn 驗證 name: $("input[name='username']").val() // 要傳給後端的參數 }; $.ajax({ url: ajax_params.ajaxurl, // ajax_params 參數在 wp_localize_script 定義 data: data, type: 'POST', dataType: "json", success: function (data) { console.log(data.log); // data 為接收回傳的參數 } }) }) })
<?php function ajax_scripts() { wp_register_script('my_ajax', plugin_dir_url( __DIR__) . '/js/poll.js', array('jquery'),null,true ); wp_localize_script('my_ajax', 'ajax_params', array( 'ajaxurl' => site_url(). '/wp-admin/admin-ajax.php', // WordPress AJAX URL 'nonce' => wp_create_nonce('ajax-nonce'), // TOKEN 驗證,裡面的值要跟下面的 handler 一樣 'other' => 'something' )); wp_enqueue_script('my_ajax'); } function myajax_ajax_handler(){ // TOKEN 驗證 if (!wp_verify_nonce($_POST['security'], 'ajax-nonce')) { // 第二個參數要跟上面的 wp_create_nonce 的一樣 wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求')); } echo json_encode( array( 'result'=>'Ajax Success', // 把 php 參數編譯為 json 檔讓傳給 js ) ); die; } add_action('wp_enqueue_scripts', ajax_scripts); add_action('wp_ajax_myajax', myajax_ajax_handler); add_action('wp_ajax_nopriv_myajax', myajax_ajax_handler);
Tags:
- ajax
- /
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:
- ajax
- /