Get related terms by parent term with REST API
PHP
if(!class_exists('ODS_REST_API')){ /** * 取得圖片主分類的關聯分類 * * 範例:取得國家 term id 773 的關聯地區 * https://example.com/wp-json/ods/v1/area/773 */ class ODS_REST_API { private $related_area_data; /** * */ public function get_temrs_by_related( $request ) { $related_area = get_field( 'country_related_area', $request['tax'].'_tax_'.$request['id']); foreach($related_area as $data) { $this->related_area_data[] = [ 'term_id' => $data->term_id, 'name' => $data->name ]; } if ( $related_area ) { return rest_ensure_response( $this->related_area_data ); } else { return new WP_Error( 'rest_product_invalid', 'The term does not exist.', array( 'status' => 404 ) ); } return new WP_Error( 'rest_api_sad', 'Something went horribly wrong.', array( 'status' => 500 ) ); } /** * */ public function register_terms_route() { register_rest_route( 'ods/v1', '/(?<tax>[a-z]+)/(?P<id>[\d]+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array($this,'get_temrs_by_related'), )); } } } $term_route = new ODS_REST_API(); add_action( 'rest_api_init', array( $term_route, 'register_terms_route') );
Tags:
- register_rest_route
- /
- rest-api
- /
- taxonomy
- /
- term
- /
Send variables to template
// in archive, taxonomy <?php $tax = 'news_tax'; ?> <ul class="uk-margin-medium-bottom uk-margin-medium-top uk-grid-match [email protected] [email protected] uk-grid-small" uk-grid=""> <?php while($i->have_posts()): $i->the_post(); ?> <?php if($i->current_post > 0): ?> <!-- <loopCardPrimary>--> <?php set_query_var('tax', $tax); ?> <?php echo get_template_part('partials/loops/card-primary'); ?> <!-- </loopCardPrimary>--> <?php endif; ?> <?php endwhile; wp_reset_postdata(); ?> </ul> // in loop template <?php $tax = get_query_var('tax'); ?>
Single Post Navigation
Thumbnail

// <PageNav> .uk-margin-top.uk-margin-bottom .uk-grid-collapse.uk-padding.uk-padding-remove-horizontal.uk-child-width-1-2.uk-grid-divider.grid-divider-secondary(uk-grid) div a(href='#') .uk-position-relative i.uk-position-center-left.uk-text-secondary(uk-icon='icon:chevron-left; ratio: 2;' style='left: -.5rem;') .uk-grid-small.uk-margin-left(uk-grid) div(class='[email protected] [email protected]') .uk-width-1-1.uk-background-cover.uk-display-block(data-src="img/default_image.png" uk-img style="padding-top: calc(115 / 172 * 100%);") div(class='[email protected]') p.text-white.text-xsmall.uk-text-center(class='[email protected]') span.uk-background-secondary.uk-position-relative(style='top: .2rem; padding: .2rem .5rem;' class='[email protected]') PREV | 上一篇 span.uk-background-secondary.uk-position-relative.text-remove-spacing.uk-text-nowrap(style='top: 0; padding: .2rem .5rem;' class='[email protected]') PREV | 上一篇 p.text-medium-m.text-default.uk-padding-default-top.uk-text-bold(class='[email protected]' style='letter-spacing: .9px; line-height: 1.94') AA div a(href='#') .uk-position-relative i.uk-position-center-right.uk-text-secondary(uk-icon='icon:chevron-right; ratio: 2;' style='right: -.5rem;') .uk-grid-small.uk-margin-right(uk-grid) div(class='[email protected] [email protected]') .uk-width-1-1.uk-background-cover.uk-display-block(data-src="img/default_image.png" uk-img style="padding-top: calc(115 / 172 * 100%);") div(class='[email protected] padding-remove-left-s') p.text-white.text-xsmall.uk-text-center(class='[email protected]') span.uk-background-secondary.uk-position-relative(style='top: .2rem; padding: .2rem .5rem;' class='[email protected]') NEXT | 下一篇 span.uk-background-secondary.uk-position-relative.text-remove-spacing.uk-text-nowrap(style='top: 0; padding: .2rem .5rem;' class='[email protected]') NEXT | 下一篇 p.text-medium-m.text-default.uk-padding-default-top.uk-text-bold(class='[email protected]' style='letter-spacing: .9px; line-height: 1.94') BB // </PageNav>
.uk-grid-divider.grid-divider-secondary > :not(.uk-first-column)::before { border-color: $global-secondary-background; }
<div class="uk-margin-top uk-margin-bottom"> <div class="uk-grid-collapse uk-padding uk-padding-remove-horizontal uk-child-width-1-2 uk-grid-divider grid-divider-secondary" uk-grid=""> <div> <?php if(get_previous_post()): ?> <a href="<?php echo esc_url(get_previous_post()->guid); ?>"> <div class="uk-position-relative"> <i class="uk-position-center-left uk-text-secondary" uk-icon="icon:chevron-left; ratio: 2;" style="left: -.5rem;"></i> <div class="uk-grid-small uk-margin-left" uk-grid=""> <div class="[email protected] [email protected]"> <div class="uk-width-1-1 uk-background-cover uk-display-block" data-src="<?php echo esc_url(get_the_post_thumbnail_url(get_previous_post()->ID),'full'); ?>" uk-img="" style="padding-top: calc(115 / 172 * 100%);"></div> </div> <div class="[email protected]"> <p class="text-white text-xsmall uk-text-center [email protected]"><span class="uk-background-secondary uk-position-relative [email protected]" style="top: .2rem; padding: .2rem .5rem;">PREV | 上一篇</span><span class="uk-background-secondary uk-position-relative text-remove-spacing uk-text-nowrap [email protected]" style="top: 0; padding: .2rem .5rem;">PREV | 上一篇</span></p> <p class="text-medium-m text-default uk-padding-default-top uk-text-bold [email protected]" style="letter-spacing: .9px; line-height: 1.94"><?php echo esc_html(get_previous_post()->post_title); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> <div> <?php if(get_next_post()): ?> <a href="<?php echo esc_url(get_next_post()->guid); ?>"> <div class="uk-position-relative"> <i class="uk-position-center-right uk-text-secondary" uk-icon="icon:chevron-right; ratio: 2;" style="right: -.5rem;"></i> <div class="uk-grid-small uk-margin-right" uk-grid=""> <div class="[email protected] [email protected]"> <div class="uk-width-1-1 uk-background-cover uk-display-block" data-src="<?php echo esc_url(get_the_post_thumbnail_url(get_next_post()->ID),'full'); ?>" uk-img="" style="padding-top: calc(115 / 172 * 100%);"></div> </div> <div class="[email protected] padding-remove-left-s"> <p class="text-white text-xsmall uk-text-center [email protected]"><span class="uk-background-secondary uk-position-relative [email protected]" style="top: .2rem; padding: .2rem .5rem;">NEXT | 下一篇</span><span class="uk-background-secondary uk-position-relative text-remove-spacing uk-text-nowrap [email protected]" style="top: 0; padding: .2rem .5rem;">NEXT | 下一篇</span></p> <p class="text-medium-m text-default uk-padding-default-top uk-text-bold [email protected]" style="letter-spacing: .9px; line-height: 1.94"><?php echo esc_html(get_next_post()->post_title); ?></p> </div> </div> </div> </a> <?php endif; ?> </div> </div> </div>
Single Post Tag List
Thumbnail

each i in single each j in i.tag .uk-grid-small.uk-margin-medium-top(uk-grid) div(style='width: 25px') img(src='img/icon-tag.svg') .uk-width-expand ul.uk-flex.uk-flex-wrap each k in j.list li.uk-margin-small-bottom a.uk-button.button-secondary-outline.text-small.uk-margin-small-left.uk-text-nowrap(href=k.href)=k.text
.button-secondary-outline { border: 1px solid $global-secondary-background; color: $global-secondary-background; &:hover { color: #fff; background-color: $global-secondary-background; } }
Footer with mega menu
Organize sub menu with menu_item_parent.
Thumbnail

// <footerNav> .uk-background-primary p.uk-text-center.text-white.uk-padding-default-top a(href='#top' uk-scroll) img.text-white(src='img/icon-backtotop.svg' uk-svg) .uk-container.uk-padding // <nav> .uk-grid-match.grid-divider-first.uk-margin-medium-bottom(uk-grid class='[email protected] uk-child-width-1-2') each i in footer each j in i.nav div section h3.text-medium.uk-text-bold.text-white(style='letter-spacing: 1.8px; margin-bottom: 25px;')=j.title ul.uk-list() each k in j.navItems li.uk-margin-default-bottom a.text-small.text-white.link-secondary(href=k.href style='letter-spacing: 1.4px')=k.text // </nav> hr.uk-margin-remove(style='border-color:#2e586c') // <navPolicy> nav.uk-navbar-container.uk-flex-wrap(uk-navbar="") .uk-navbar-left ul.uk-navbar-nav.navbar-divider each i in footer each j in i.navPolicy li a.text-white.link-secondary(href=j.href style='letter-spacing: 1.6px;')=j.title .uk-navbar-right ul.uk-navbar-nav li a.text-white.link-secondary(href="#") i(uk-icon='icon:facebook;ratio:1.2') li a.text-white.link-secondary(href="#") i(uk-icon='icon:twitter;ratio:1.2') li a.text-white.link-secondary(href="#") i(uk-icon='icon:linkedin;ratio:1.2') li a.text-white.link-secondary(href="#") i(uk-icon='icon:youtube;ratio:1.2') li a.text-white.link-secondary(href="#") i(uk-icon='icon:pinterest;ratio:1.2') li a.text-white.link-secondary(href="#") i(uk-icon='icon:google;ratio:1.2') // </navPolicy> hr.uk-margin-remove(style='border-color:#2e586c') // <copyRight> .uk-flex.uk-padding-small.uk-padding-default-top.uk-padding-remove-bottom.uk-flex-middle.uk-flex-wrap(class='[email protected] uk-flex-center') a(href='#') img(src='img/logo.jpg') p.uk-display-block(class='[email protected]' style='width:100%;') p.uk-text-right.text-white.text-xsmall(class='[email protected] uk-text-center') Copyright © Pools Corp. All rights reserved. // </copyRight> // </footerNav>
.footer { .uk-navbar-container { padding: 62px 0; @include mq-m{ padding: 30px 0; } } .uk-navbar-container:not(.uk-navbar-transparent) { background: transparent; } .uk-navbar-nav>li>a { min-height: auto; padding:0 26px; @include mq-s{ padding: 0 10px; } @include mq(375px){ font-size: rem(12px); } } .uk-navbar-right{ .uk-navbar-nav>li>a { padding: 0 11px; } } @include mq-s { .uk-navbar-left, .uk-navbar-right { margin-left: auto; margin-right: auto; } } }
<div class="uk-grid-match grid-divider-first uk-margin-medium-bottom [email protected] uk-child-width-1-2" uk-grid=""> <?php foreach(wp_get_nav_menu_items('footer') as $nav): ?> <?php if($nav->menu_item_parent === '0'): ?> <div> <section> <h3 class="text-medium uk-text-bold" style="letter-spacing: 1.8px; margin-bottom: 25px;"> <a class="text-white" href="<?php echo esc_attr($nav->url); ?>"><?php echo esc_attr($nav->title); ?></a> </h3> <ul class="uk-list text-white"> <?php foreach(wp_get_nav_menu_items('footer') as $i): ?> <?php if($i->menu_item_parent != 0 && $nav->ID == $i->menu_item_parent): ?> <li class="uk-margin-default-bottom"><a class="text-small text-white link-secondary" href="<?php echo $i->url; ?>" style="letter-spacing: 1.4px"><?php echo $i->title; ?></a></li> <?php endif; ?> <?php endforeach; ?> </ul> </section> </div> <?php endif; ?> <?php endforeach; ?> </div>
Tags:
- menu
- /
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
- /
Delete posts in frontend
DOMJSPHP
<ul class="[email protected] [email protected]" uk-grid> <?php $args_post = array( 'posts_per_page' => -1, 'post_type' => 'post', 'post_status' => 'any', 'author' => wp_get_current_user()->ID ); $query_post = new WP_Query( $args_post ); if( $query_post->have_posts() ): while( $query_post->have_posts() ): $query_post->the_post();?> <li class="uk-position-relative link-cover"> <div class="uk-width-1-1 uk-background-default height-400 uk-position-relative uk-background-cover" data-src="<?php echo get_field('cover_src'); ?>" uk-img style="border-radius: 10px; box-shadow: 3px 3px 10px 0px rgba(0,0,0,0.5); overflow: hidden"> <div class="cover uk-position-top-left" style="width:100%;height:100%;background-color:rgba(0,0,0,0.5)"> <ul class="uk-flex uk-position-center uk-position-small uk-flex-around" style="width:80%"> <li><a class="uk-button uk-button-primary text-white text-xsmall uk-border-rounded" href="<?php echo home_url(); ?>/editor?post=<?php echo get_the_ID(); ?>" style="padding: 0 15px;">編輯</a></li> <li><a class="uk-button uk-button-primary text-white text-xsmall uk-border-rounded" href="<?php the_permalink(); ?>" target="_blank" rel="noopener norefererr" style="padding: 0 15px;">預覽</a></li> <li><a class="uk-button uk-button-danger text-white text-xsmall uk-border-rounded btnDelete" href="#" data-id="<?php echo get_the_ID(); ?>" style="padding: 0 15px;">刪除</a></li> <?php wp_nonce_field( 'ajax-delete-nonce', 'security' ); ?> </ul> </div> </div> <h3 class="uk-text-center uk-margin text-default-height"><?php the_title(); ?></h3> </li> </ul>
<script> var $ = jQuery.noConflict(); $(function(){ $('.btnDelete').on('click', function(){ var r = confirm('確定要刪除?'); if(r){ action = 'deletepost'; postid = $(this).attr('data-id'); security = $('#security').val(); $.ajax({ url: delete_params.ajaxurl, type: 'POST', dataType: 'json', data: { 'action': action, 'postId': postid, 'security': security }, success: function (data) { alert(data.msg); window.location.reload(); } }); } }) }) </script>
<?php function delete_scripts() { global $wp_query; wp_register_script( 'delete_post', '', '',null ); wp_localize_script( 'delete_post', 'delete_params', array( 'ajaxurl' => site_url(). '/wp-admin/admin-ajax.php' )); wp_enqueue_script( 'delete_post' ); } add_action( 'wp_enqueue_scripts', 'delete_scripts' ); function delete_ajax_handler(){ $nonce = $_POST['security']; if (!wp_verify_nonce($nonce, 'ajax-delete-nonce')) { wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求')); } $post_id = $_POST['postId']; wp_delete_post($post_id, true); echo json_encode( array( 'msg'=>"刪除成功!", ) ); die; } add_action('wp_ajax_deletepost', 'delete_ajax_handler');
Add body css class name by template tag
PHP
// 加入 body class 名稱 function add_slug_to_body_class($classes) { global $post; if (is_front_page()) { $key = array_search('blog', $classes); if ($key > -1) { unset($classes[$key]); } } elseif (is_page()) { $classes[] = sanitize_html_class($post->post_name); // 確保只會有英數當 class } elseif (is_singular()) { $classes[] = sanitize_html_class($post->post_name); } return $classes; } add_filter('body_class', 'add_slug_to_body_class');
Register custom taxonomy in array
PHP
function add_post_taxonomy() { $taxArray = array( array( "taxName" => 'tax中文名', "taxNameEn" =>'taxSlu' ), ); foreach ($taxArray as $tax) { $labels = array( "name" => __( "", "" ), "singular_name" => __( $tax['taxName'], "" ), "menu_name" => __( $tax['taxName'], "" ), "all_items" => __( "所有", "" ), "edit_item" => __( "編輯", "" ), "view_item" => __( "檢視", "" ), "update_item" => __( "更新", "" ), "add_new_item" => __( "新增", "" ), "new_item_name" => __( "新增", "" ), "search_items" => __( "搜尋", "" ), ); $args = array( "label" => __( $tax['taxName'], "" ), "labels" => $labels, "public" => true, "hierarchical" => true, "label" => $tax['taxName'], "show_ui" => true, "show_in_menu" => true, "show_in_nav_menus" => true, "show_admin_column" => true, "query_var" => true, "rewrite" => array( 'slug' => $tax['taxNameEn'], 'with_front' => true, ), "show_admin_column" => true, "show_in_rest" => false, "rest_base" => $tax['taxNameEn'], "show_in_quick_edit" => true, ); register_taxonomy( $tax['taxNameEn'], 'post', $args ); } } add_action( 'init', 'add_post_taxonomy' );