Set sortable admin column with ACF field

<?php
function admin_columns($columns) {
  $columns = array(
    'cb'	 	=> '<input type="checkbox" />',
    'title' => '標題',
    'user' => '會員',
    'answser' => '選項',
    'date' => '日期'
  );
  return $columns;
}
function admin_columns_values($column) {
  global $post;
  switch ($column) {
    case 'user':
      echo get_field('pollresult_user')['display_name'];
      break;
    case 'date':
      echo get_the_date('Y / m / d');
      break;
    default:
      # code...
      break;
  }
}
function admin_columns_sortable( $columns ){
  $columns['user'] = '會員';
  return $columns;
}
add_filter("manage_edit-pollresult_columns", "admin_columns");
add_action("manage_pollresult_posts_custom_column", "admin_columns_values");
add_filter("manage_edit-pollresult_sortable_columns", "admin_columns_sortable" );

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:

Change role name

PHP
function wps_change_role_name() {
  global $wp_roles;
  if ( ! isset( $wp_roles ) )
    $wp_roles = new WP_Roles();
    $wp_roles->roles['subscriber']['name'] = '會員';
    $wp_roles->role_names['subscriber'] = '會員';
  }
add_action('init', 'wps_change_role_name');

Non-administrator will be redirected to the frontend page when getting into wp-admin

PHP
function my_login_redirect( $url, $request, $user ){
	if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
		if( $user->has_cap( 'administrator' ) ) {
			$url = admin_url();
		} else {
			$url = home_url('/my-account/');
		}
	}
	return $url;
}
add_filter('login_redirect', 'my_login_redirect', 10, 3 );

Custom dashboard

PHP
function remove_wp_logo( $wp_admin_bar ) { $wp_admin_bar->remove_node( 'wp-logo' ); }   /* 移除控制台左上角WP-LOGO */ 
add_action( 'admin_bar_menu', 'remove_wp_logo', 999 );


function custom_dashboard_footer () {                                                   /* 修改後台底下的wordpress文字宣告 */ 
    echo '官網維護單位 : <a href="http://abc.com/">維護單位</a>。後台如有任何問題, 請聯絡<a href="http://abc.com/">維護單位</a>'; 
} 
add_filter('admin_footer_text', 'custom_dashboard_footer');


function change_footer_admin () {return '&nbsp;';}                                      /* 隱藏後台右下角wp版本號 */ 
add_filter('admin_footer_text', 'change_footer_admin', 9999);


function change_footer_version() {return ' ';}
add_filter( 'update_footer', 'change_footer_version', 9999);

/* 強制關閉後台登入首頁的小工具 */ 
function wpc_dashboard_widgets() {
    global $wp_meta_boxes;
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);        // 活動
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);        // 現況
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);  // 近期迴響
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);   // 收到新鏈結
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);          // 外掛
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);        // 快貼
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);      // 近期草稿
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);            // WordPress Blog
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);          // Other WordPress News
}
add_action('wp_dashboard_setup', 'wpc_dashboard_widgets');

// 後台右上角會員按鈕-改成"登出"字樣
function custom_logout_link() {
    global $wp_admin_bar;
    $wp_admin_bar->add_menu( array(
        'id'    => 'wp-custom-logout',
        'title' => '登出',
        'parent'=> 'top-secondary',
        'href'  => wp_logout_url()
    ) );
    $wp_admin_bar->remove_menu('my-account');
}
add_action( 'wp_before_admin_bar_render', 'custom_logout_link' );

//移除後台上方檢視留言按鈕
//移除後台上方"+新增"按鈕
function my_admin_bar_render() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('comments');
    $wp_admin_bar->remove_menu( 'new-content' );
    $wp_admin_bar->remove_node( 'updates' );
    $wp_admin_bar->remove_node( 'view' );
}
add_action( 'wp_before_admin_bar_render', 'my_admin_bar_render' );

Custom the login page

PHP
function new_login_logo() {                                                             /* 自訂登入畫面LOGO */ 
     echo '<style type="text/css">.login h1 a { background-image:url('.get_template_directory_uri().'/assets/img/logo.svg) !important; background-size: contain!important; width:320px!important; }.login {background-image:url('.get_template_directory_uri().'/assets/img/bg-login.jpg); background-size: cover!important; background-position: 100% 50%;} #loginform,#lostpasswordform{border-radius: 20px;} .login #nav{display:none;} </style>';
}
add_action('login_head', 'new_login_logo' );


function custom_loginlogo_url($url) { return get_bloginfo('url'); }                     /* 變更自訂登入畫面上LOGO的連結 */ 
add_filter( 'login_headerurl', 'custom_loginlogo_url' );


function put_my_title(){ return ('Company Name'); }                                        /* 變更自訂登入畫面上LOGO的Hover所出現的標題 */
add_filter('login_headertext', 'put_my_title');

Add new role in author dropdown menu

PHP
function filter_authors( $args ) {
  if ( isset( $args['who'])) {
    $args['role__in'] = ['author', 'editor', 'administrator', 'innews_admin'];
		unset( $args['who']);
	}
	return $args;
}
add_action('wp_dropdown_users_args', 'filter_authors');

Inline CSS and JavaScript

PHP
function custom_admin_res() {
  echo '<style></style><script></script>';
}
add_action('admin_footer', 'custom_admin_res');

Restricting users to view only media library items they have uploaded

PHP
<?php
function users_own_attachments( $wp_query_obj ) {
    global $current_user, $pagenow;
    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');
    if( !$is_attachment_request )
        return;
    if( !is_a( $current_user, 'WP_User') )
        return;
    if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
        return;
    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->ID );
    return;
}
add_action('pre_get_posts','users_own_attachments');

Tags: