WordPress 相關設定筆記(持續更新)

WordPress 相關設定筆記(持續更新)
這邊整理了多年多力哥在使用wordpress時遇到的一些問題,都很實用,希望有幫助到大家^^

1.停用WordPress updates提醒訊息

如果你覺得WP後台的更新訊息很礙眼,其實可以將它關閉

注意:多力哥是不建議停用這些提醒訊息,因為某些更新可能與網站安全有關。

Disable Theme Updates # 3.0+
//Disable Theme Updates # 3.0+
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_themes' );
Disable Plugin Updates #3.0+
//Disable Plugin Updates #3.0+
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_plugins' );
Diasable Core Updates # 3.0+
//Diasable Core Updates # 3.0+
add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_version_check' );

2.後台去掉左上角W標誌

function annointed_admin_bar_remove() {
        global $wp_admin_bar;
        /* Remove their stuff */
        $wp_admin_bar->remove_menu('wp-logo');
}
add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);

3.上傳中文檔名

function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);

4.自訂後台新聞

//後台自訂新聞
function wpc_dashboard_widget_function() {
    echo '<p>您好,歡迎來到網站控制台。<br/>本網站是由DORIGO IMAGE團隊製作。</p>';
}
function wpc_add_dashboard_widgets() {
    wp_add_dashboard_widget('wp_dashboard_widgets', '網站訊息', 'wpc_dashboard_widget_function');
}
add_action('wp_dashboard_setup', 'wpc_add_dashboard_widgets' );

5.根據頁面類型指定每頁顯示的文章數

function custom_posts_per_page($query){
    if(is_home()){
    $query->set('posts_per_page',6);//首頁每頁顯示8篇文章
    }
    if(is_search()){
        $query->set('posts_per_page',-1);//搜索頁顯示所有匹配的文章,不分頁
    }
    if(is_archive()){
        $query->set('posts_per_page',12);//archive每頁顯示25篇文章
}//endif
}//function
//this adds the function above to the 'pre_get_posts' action
add_action('pre_get_posts','custom_posts_per_page');

6.自訂WP後台上方列選單連結

add_action( 'admin_bar_menu', 'toolbar_link', 999 );
function toolbar_link( $wp_admin_bar ) {
$args = array(
'id'    => 'my_page',
'title' => '我是選單',
'href'  => 'http://dorigo-image.com',
'meta'  => array( 'target' => '_blank' )
);
$wp_admin_bar->add_node( $args );
}

999:排序位置

7.自訂WP後台左方列子選單連結

add_action('admin_menu', 'album_menu');

function album_menu() {
global $submenu;
$url = '放網址';
$submenu['index.php'][] = array('連結名稱', 'manage_options', $url);
}

選單的位置參考(此範例為加到Dashboard):
index.php => Dashboard
edit.php => Posts
upload.php => Media
link-manager.php => Links
edit.php?post_type=page => Pages
edit-comments.php => Comments
themes.php => Appearance
plugins.php => Plugins
users.php => Users
tools.php => Tools
options-general.php => Settings

8.自訂WP後台左方列主選單連結

add_action( 'admin_menu', 'register_custom_menu_link' );
function register_custom_menu_link(){
add_menu_page( 'custom menu link', 'Your Menu Link', 'manage_options', 'any-url', 'wpsites_custom_menu_link', 'dashicons-carrot', 3 );
}
function wpsites_custom_menu_link(){
wp_redirect( 'http://dorigo-image.com', 301 );
exit;
}

參考:
http://codex.wordpress.org/Function_Reference/add_menu_page
http://codex.wordpress.org/Function_Reference/wp_redirect

9.安裝佈景主題失敗

出現:

Warning: unlink(C:\Windows\TEMP/795c043fc91788ccdf4ee17b1a402b8a.tmp) [function.unlink]: Permission denied in E:\AppServ\www\guest\wp-admin\includes\file.php on line 457

下載失敗 error:0D0C50A1:asn1 encoding routines:ASN1_item_verify:unknown message digest algorithm

解決方式:

請編輯httpd.conf

找到 #LoadModule ssl_module modules/mod_ssl.so

將註解#去掉,存檔,重啟Apache

10.移除WordPress的 wp_head 中多餘信息

remove_action( 'wp_head', 'wp_generator' ) ; 
remove_action( 'wp_head', 'wlwmanifest_link' ) ; 
remove_action( 'wp_head', 'rsd_link' ) ;

11.Contact Form 7 checkboxes斷行

span.wpcf7-list-item {
display:block;
}

若是要某些checkboxes欄位斷行某些欄位是持續的,請再加以下這行

<div class="noenter">要持續的checkboxes</div>

.noenter span.wpcf7-list-item {
	display: inline-block;
}

12.禁止多個人同時登錄一個賬號

/**
 * Detect if the current user has concurrent sessions
 *
 * @return bool
 */
function pcl_user_has_concurrent_sessions() {
    return ( is_user_logged_in() && count( wp_get_all_sessions() ) > 1 );
}
 
/**
 * Get the user's current session array
 *
 * @return array
 */
function pcl_get_current_session() {
    $sessions = WP_Session_Tokens::get_instance( get_current_user_id() );
 
    return $sessions->get( wp_get_session_token() );
}
 
/**
 * Only allow one session per user
 *
 * If the current user's session has been taken over by a newer
 * session then we will destroy their session automattically and
 * they will have to login again to continue.
 *
 * @action init
 *
 * @return void
 */
function pcl_disallow_account_sharing() {
    if ( ! pcl_user_has_concurrent_sessions() ) {
        return;
    }
 
    $newest  = max( wp_list_pluck( wp_get_all_sessions(), 'login' ) );
    $session = pcl_get_current_session();
 
    if ( $session['login'] === $newest ) {
        wp_destroy_other_sessions();
    } else {
        wp_destroy_current_session();
    }
}
add_action( 'init', 'pcl_disallow_account_sharing' );

13.自動幫文章裡的URL地址生成超鏈接

add_filter('the_content', 'make_clickable');

若要開新視窗

// Make URL Clickable In WordPress (plus target="_blank")

add_filter( 'the_content', 'make_clickable');

function autoblank($text) {
$myurl = 'http://yourname.com';
$external = str_replace('href=', 'target="_blank" href=', $text);
$external = str_replace('target="_blank" href="'.$myurl, 'href="'.$myurl, $external);
$external = str_replace('target="_blank" href="#', 'href="#', $external);
$external = str_replace('target = "_blank">', '>', $external);
return $external;
}
add_filter('the_content', 'autoblank');

14.將全站設為需登入才可瀏覽

可看到首頁:

function admin_redirect() {
   if ( !is_front_page() && !is_user_logged_in()) {
       wp_redirect( home_url('wp-login.php') );
       exit;
   }
}
add_action('get_header', 'admin_redirect');

不可看到首頁:

function admin_redirect() {
   if ( !is_user_logged_in()) {
       wp_redirect( home_url('wp-login.php') );
       exit;
   }
}
add_action('get_header', 'admin_redirect');

15.登入後導到前台

function redirect_to_front_page() {
global $redirect_to;
if (!isset($_GET['redirect_to'])) {
$redirect_to = get_option('siteurl');
}
}
add_action('login_form', 'redirect_to_front_page');

登入後導到特定頁面:

function redirect_page( $redirect_to, $request, $user )
{
    return 'http://xxx.xxx.xxx';
}
add_filter( 'login_redirect', 'redirect_page' );

16.對特定使用者登入後導到前台

add_filter( 'login_redirect', 'redirect_to_home', 10, 3 );
function redirect_to_home( $redirect_to, $request, $user ) {

    if( $user->ID == 2 ) {
        //If user ID is 2, redirect to home
        return get_home_url();
    } else {
        //If user ID is not 2, leave WordPress handle the redirection as usual
        return $redirect_to;
    }

}

17.禁止一般用戶進入後台

function baw_no_admin_access()
{
if( !current_user_can( 'manage_options' ) ) {
wp_redirect( home_url() );
die();
}
}
add_action( 'admin_init', 'baw_no_admin_access', 1 );

18.Rocket Lazy Load 設定頁面不要延遲加載圖片

add_action( 'wp', 'deactivate_rocket_lazyload_on_single' );
function deactivate_rocket_lazyload_on_single() {
    if ( is_page() ) {
        add_filter( 'do_rocket_lazyload', '__return_false' );
    }
}

18.重設WordPress密碼

將此resetpassword.php檔放到網站根目錄,然後開啟瀏覽器讀取,就可以重設密碼。

設定完成後請記得刪除^^

19.圖片可用子網址

例如:http://img.yourname.com
因為網站在讀取的時候網址會有連線數的限制,如果把網站跟圖片分成兩個網址則可以讓連線數加倍

20.文章列表只顯示標題

編輯wp-content/themes/xxx/index.php

php the_content('Read the rest of this entry »');

替換成:

php
if (is_single()) {
the_content('Read the rest of this entry »');
}
else {//no content, nothing.
}

21.去除後台標題中的— WordPress

//WordPress 去除後台標題中的「—— WordPress」

add_filter('admin_title', 'wpdx_custom_admin_title', 10, 2);
function wpdx_custom_admin_title($admin_title, $title){
return $title.' &lsaquo; '.get_bloginfo('name');
}

22.文章編輯器加入中文字型

add_filter( 'mce_buttons' , 'add_font_selection_to_tinymce' );
function add_font_selection_to_tinymce($buttons) {
     array_push($buttons, 'fontselect');
     return $buttons;
}
add_filter( 'tiny_mce_before_init', 'use_my_fonts_to_tinymce' );
function use_my_fonts_to_tinymce( $initArray ) {
$theme_advanced_fonts .= '標楷體=標楷體;';
$theme_advanced_fonts .= '微軟正黑體=微軟正黑體;';
$theme_advanced_fonts .= '新細明體=新細明體;';
$initArray['font_formats'] = $theme_advanced_fonts;
return $initArray;
}

23.後台文章列表顯示特色圖片

add_theme_support('post-thumbnails');

function ST4_columns_head($defaults) {
$defaults['featured_image'] = '特色圖片';
return $defaults;
}
function ST4_columns_content($column_name, $post_ID) {
if ($column_name == 'featured_image') {
$post_thumbnail_id = get_post_thumbnail_id($post_ID);
if ($post_thumbnail_id) {
$post_thumbnail_img = wp_get_attachment_image_src($post_thumbnail_id);
if ( $post_thumbnail_img[0] ){
echo '<img src="' . $post_thumbnail_img[0] . '" />';
}
}
}
}

add_filter('manage_posts_columns', 'ST4_columns_head');
add_action('manage_posts_custom_column', 'ST4_columns_content', 10, 2);

24.修改網站後台介面的CSS

新增一個custom-admin.css檔把你要修改的CSS屬性加上去,檔案放到佈景主題的目錄中

1
2
3
4
5
//新增一個CSS載入後台
function admin_css() {
wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/custom-admin.css' );
}
add_action('admin_print_styles', 'admin_css' );

25.修改後台登錄LOGO和連結

/* WordPress登錄界面Logo和鏈接修改開始 */

function my_custom_login_logo() {
    echo '<style type="text/css">
        h1 a { background-image:url(https://xxx.com/xxx.jpg) !important; background-size: inherit !important; width: 330px; height: 130px; }
    </style>';
}
add_action('login_head', 'my_custom_login_logo');

function custom_loginlogo_url($url) {
    return "http://web.hahasmile.com";
}
add_filter( 'login_headerurl', 'custom_loginlogo_url' );
/* WordPress登錄界面Logo和鏈接修改結束 */

26.wordpress標籤排序數量修改

編輯/wp-includes/category-template.php,搜尋 wp_tag_cloud

function wp_tag_cloud( $args = '' ) {
	$defaults = array(
		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 40,
		'format' => 'flat', 'separator' => "\n", 'orderby' => 'count', 'order' => 'DESC',
		'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomy' => 'post_tag', 'post_type' => '', 'echo' => true
	);

27.如何解決網站出現 Briefly Unavailable for Scheduled Maintenance Error

出現"因例行維護而暫時無法存取。請稍後再來。"

請至網站根目錄,刪除.maintenance 檔案即可

28.在你變更固定網址後,如何讓舊文章能對應到新網址做301轉址

為了避免變更網址後,搜尋引擎還未收錄新的網址,使用者會出現網頁404錯誤,我們要馬上做301轉址
怎麼做?請參考這篇文章

29.行動裝置瀏覽時在文章中插入LINE分享按鈕

<div class="linephone">
<p align=center><a href="http://line.naver.jp/R/msg/text/?<?php the_title(); ?>%20%0a<?php the_permalink(); ?>"><img src="https://miupix.cc/di/5IBQS8/pbq49tq.png"></a></p>
</div>

@media screen and (min-width:640px) {
.linephone {display:none;}
}

30.開啟Wordpress 隱藏的 Admin Options

http://yoursite.com/wp-admin/options.php

31.行動裝置瀏覽時網站隱藏部分區塊(side、footer等等)

@media screen and (max-width: 800px){
#main-footer  {
display: none;
}}

32.安裝wordpress APP

https://play.google.com/store/apps/details?id=org.wordpress.android

33.移除Emoji Script and Style

// Remove emoji support.
function myg_remove_emoji() {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );

// Remove from TinyMCE
add_filter( 'tiny_mce_plugins', 'myg_remove_tinymce_emoji' );
}
add_action( 'init', 'myg_remove_emoji' );

// Filter out the tinymce emoji plugin.

function myg_remove_tinymce_emoji( $plugins ) {

if ( ! is_array( $plugins ) ) {
return array();
}

return array_diff( $plugins, array( 'wpemoji' ) );
}

34.Redirect Attachment Pages To The Parent Post URL

add_action( 'template_redirect', 'wpsites_attachment_redirect' );
function wpsites_attachment_redirect(){
global $post;
if ( is_attachment() && isset($post->post_parent) && is_numeric($post->post_parent) && ($post->post_parent != 0) ) :
wp_redirect( get_permalink( $post->post_parent ), 301 );
exit();
wp_reset_postdata();
endif;
}

35.移除小工具"其他"中的部分連結只留下登出登入

請到\wp-includes\widgets編輯class-wp-widget-meta.php
將以下這段程式碼註解掉:

<li><a href="<?php echo esc_url( get_bloginfo( 'rss2_url' ) ); ?>"><?php _e('Entries <abbr title="Really Simple Syndication">RSS</abbr>'); ?></a></li>
<li><a href="<?php echo esc_url( get_bloginfo( 'comments_rss2_url' ) ); ?>"><?php _e('Comments <abbr title="Really Simple Syndication">RSS</abbr>'); ?></a></li>
<?php
/**
* Filters the "Powered by WordPress" text in the Meta widget.
*
* @since 3.6.0
*
* @param string $title_text Default title text for the WordPress.org link.
*/
echo apply_filters( 'widget_meta_poweredby', sprintf( '<li><a href="%s" title="%s">%s</a></li>',
esc_url( __( 'https://wordpress.org/' ) ),
esc_attr__( 'Powered by WordPress, state-of-the-art semantic personal publishing platform.' ),
_x( 'WordPress.org', 'meta widget link text' )
) );

wp_meta();

36.新增帳號角色時移除管理者選項

function wpse_40897_filter_get_editable_roles_for_new_user( $editable_roles ) {
global $pagenow;
if ( 'user-new.php' == $pagenow ) {
unset( $editable_roles['administrator'] );
}
return $editable_roles;

}
add_filter( 'editable_roles', 'wpse_40897_filter_get_editable_roles_for_new_user' );

37.帳號列表不要顯示角色為administrator的帳號

add_action('pre_user_query','yoursite_pre_user_query');
function yoursite_pre_user_query($user_search) {
$user = wp_get_current_user();
if ($user->ID!=1) { // Is not administrator, remove administrator
global $wpdb;
$user_search->query_where = str_replace('WHERE 1=1',
"WHERE 1=1 AND {$wpdb->users}.ID<>1",$user_search->query_where);
}
}

38.WP Super Cache啟動失敗 No such file or directory in...

通常是在搬移網站時會出現,解決步驟如下:
刪除wp-config.php中的
define( 'WPCACHEHOME', '/wp-content/plugins/wp-super-cache/' ); //Added by WP-Cache Manager
停用並刪除WP Super Cache
重新安裝WP Super Cache
啟動,應可順利執行

39.後台媒體庫只顯示目前登入使用者自己上傳的文件

/**
* WordPress 媒體庫只顯示用戶自己上傳的文件
*/
//在文章編輯頁面的[添加媒體]只顯示用戶自己上傳的文件
function my_upload_media( $wp_query_obj ) {
global $current_user, $pagenow;
if( !is_a( $current_user, 'WP_User') )
return;
if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
return;
if( !current_user_can( 'manage_options' ) && !current_user_can('manage_media_library') )
$wp_query_obj->set('author', $current_user->ID );
return;
}
add_action('pre_get_posts','my_upload_media');

//在[媒體庫]只顯示用戶上傳的文件
function my_media_library( $wp_query ) {
if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
if ( !current_user_can( 'manage_options' ) && !current_user_can( 'manage_media_library' ) ) {
global $current_user;
$wp_query->set( 'author', $current_user->id );
}
}
}
add_filter('parse_query', 'my_media_library' );

40.後台媒體庫篩選條件增加"作者"(不適用Grid View)

function media_add_author_dropdown()
{
$scr = get_current_screen();
if ( $scr->base !== 'upload' ) return;

$author   = filter_input(INPUT_GET, 'author', FILTER_SANITIZE_STRING );
$selected = (int)$author > 0 ? : '-1';
$args = array(
'show_option_none'   => 'All Authors',
'name'               => 'author',
'selected'           => $selected
);
wp_dropdown_users( $args );
}
add_action('restrict_manage_posts', 'media_add_author_dropdown');

41.搜尋結果顯示媒體檔案

function attachment_search( $query ) {
if ( $query->is_search ) {
$query->set( 'post_type', array( 'post', 'attachment' ) );
$query->set( 'post_status', array( 'publish', 'inherit' ) );
}

return $query;
}

42.errorlog出現Open_basedir restriction in effect. File(X) is not within the allowed path(s): Y

編輯php.ini
將open_basedir註解掉

43.更改Contact form 7 欄位的寬度高度

用手機看Contact form 7表單時,欄位可能會太寬,我們可以添加CSS屬性,讓欄位寬度為裝置的100%:

1
2
3
.wpcf7 input.wpcf7-text { width: 100%; }
.wpcf7 textarea.wpcf7-textarea { width: 100%; }
.wpcf7-form textarea { height: 200px; }
與大家分享...
WordPress 相關設定筆記(持續更新)
Facebook
0WordPress 相關設定筆記(持續更新)
Google+
0WordPress 相關設定筆記(持續更新)
Pinterest
0WordPress 相關設定筆記(持續更新)
email
0 回復

發表評論

想要留言嗎?
歡迎歡迎!

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *