WordPress常用主題功能函數(shù)

<?php

//--------------------------------------------------------引入后臺(tái)框架----------------------------------------------------

//導(dǎo)入ReduxFrameWork框架
//if ( !class_exists( 'ReduxFramework' ) && file_exists( dirname( __FILE__ ) . '/admin/ReduxCore/framework.php' ) ) {
//  require_once( dirname( __FILE__ ) . '/admin/ReduxCore/framework.php' );
//}
//if ( !isset( $redux_demo ) && file_exists( dirname( __FILE__ ) . '/admin/config.php' ) ) {
//  require_once( dirname( __FILE__ ) . '/admin/config.php' );
//}

//通過(guò)這段代碼褪猛,對(duì)語(yǔ)言包進(jìn)行翻譯,需要將語(yǔ)言包的代碼添加到調(diào)用主題選項(xiàng)代碼的前面(目前不確定是加在哪里)
//load_theme_textdomain('ankium', get_template_directory() . '/languages');

//引入后臺(tái)框架CodeStarFramework
require_once dirname( __FILE__ ) .'/codestar/cs-framework.php';

//---------------------------------------------------------后臺(tái)訂制------------------------------------------------------

/*
 * 移除Wordpress后臺(tái)頂部左上角的W圖標(biāo)
 */
add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0);
function annointed_admin_bar_remove() {
    global $wp_admin_bar;
    /* Remove their stuff */
    $wp_admin_bar->remove_menu('wp-logo');
}


/*
 * 自定義后臺(tái)登錄Logo的Url
 */
add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
    return 'http://www.ankium.com';
}


/*
 * 自定義 WordPress 后臺(tái)底部的版權(quán)和版本信息
 */
add_filter('admin_footer_text', 'left_admin_footer_text');
function left_admin_footer_text($text) {
    // 左邊信息
    $text = '大道行思,開(kāi)拓創(chuàng)新辨图;大道至簡(jiǎn)员凝,務(wù)實(shí)為要';
    return $text;
}
add_filter('update_footer', 'right_admin_footer_text', 11);
function right_admin_footer_text($text) {
    // 右邊信息
    $text = "延安安琪云信息科技有限公司";
    return $text;
}


/*
 * 屏蔽 WP 后臺(tái)“顯示選項(xiàng)”和“幫助”選項(xiàng)卡
 */
//add_filter('screen_options_show_screen', 'remove_screen_options');
//add_filter( 'contextual_help', 'remove_wp_help', 999, 3 );
function remove_screen_options(){ return false;}
function remove_wp_help($old_help, $screen_id, $screen){
    $screen->remove_help_tabs();
    return $old_help;
}

/*
 * 固定后臺(tái)管理側(cè)邊欄
 */
add_action('admin_head', 'Bing_fixed_adminmenuwrap');
function Bing_fixed_adminmenuwrap(){
    echo '<style type="text/css">#adminmenuwrap{position:fixed;left:0px;z-index:2;}</style>';
};


/*
 * 阻止站內(nèi)文章互相Pingback
 */
add_action('pre_ping','Bing_noself_ping');
function Bing_noself_ping($links) {
    $home = get_option( 'home' );
    foreach ( $links as $l => $link )
        if ( 0 === strpos( $link, $home ) )
            unset($links[$l]);
}

/*
 * 增強(qiáng)默認(rèn)編輯器(mce_buttons:工具欄的第一行;mce_buttons_2:工具欄第二行严卖;mce_buttons_3:工具欄第三行)
 */
add_filter("mce_buttons", "Bing_editor_buttons");
function Bing_editor_buttons($buttons){

    //$buttons[] = 'wp_adv';        //隱藏按鈕顯示開(kāi)關(guān)
    $buttons[] = 'wp_adv_start';    //隱藏按鈕區(qū)起始部分
    $buttons[] = 'wp_adv_end';      //隱藏按鈕區(qū)結(jié)束部分
    //$buttons[] = 'bold';          //加粗
    //$buttons[] = 'italic';        //斜體
    $buttons[] = 'underline';       //下劃線
    $buttons[] = 'strikethrough';   //刪除線
    $buttons[] = 'justifyleft';     //左對(duì)齊
    $buttons[] = 'justifycenter';   //居中
    $buttons[] = 'justfyright';     //右對(duì)齊
    $buttons[] = 'justfyfull';      //兩端對(duì)齊
    //$buttons[] = 'bullist';       //無(wú)序列表
    //$buttons[] = 'numlist';       //編號(hào)列表
    $buttons[] = 'outdent';         //減少縮進(jìn)
    $buttons[] = 'indent';          //縮進(jìn)
    $buttons[] = 'cut';             //剪切
    $buttons[] = 'copy';            //復(fù)制
    $buttons[] = 'paste';           //粘貼
    $buttons[] = 'undo';            //撤銷
    $buttons[] = 'redo';            //重做
    //$buttons[] = 'link';          //插入超鏈接
    $buttons[] = 'unlink';          //取消超鏈接
    $buttons[] = 'image';           //插入圖片
    $buttons[] = 'removeformat';    //清除格式
    $buttons[] = 'code';            //打開(kāi)HTML代碼編輯器
    $buttons[] = 'hr';              //水平線
    $buttons[] = 'cleanup';         //清除冗余代碼
    $buttons[] = 'formmatselect';   //格式選擇
    $buttons[] = 'fontselect';      //字體選擇
    $buttons[] = 'fontsizeselect';  //字號(hào)選擇
    $buttons[] = 'styleselect';     //樣式選擇
    $buttons[] = 'sub';             //上標(biāo)
    $buttons[] = 'sup';             //下標(biāo)
    $buttons[] = 'forecolor';       //字體顏色
    $buttons[] = 'backcolor';       //字體背景色
    $buttons[] = 'charmap';         //特殊符號(hào)
    $buttons[] = 'anchor';          //錨文本
    $buttons[] = 'newdocument';     //新建文本
    //$buttons[] = 'wp_more';       //插入more標(biāo)簽
    $buttons[] = 'wp_page';         //插入分頁(yè)標(biāo)簽
    $buttons[] = 'spellchecker';    //拼寫(xiě)檢查
    $buttons[] = 'wp_help';         //幫助
    //$buttons[] = 'selectall';       //全選
    //$buttons[] = 'visualaid';       //顯示/隱藏指導(dǎo)線和不可見(jiàn)元素
    $buttons[] = 'spellchecker';    //切換拼寫(xiě)檢查器狀態(tài)
    $buttons[] = 'pastetext';       //以純文本粘貼
    $buttons[] = 'pasteword';       //從Word中粘貼
    //$buttons[] = 'blockquote';      //引用
    $buttons[] = 'forecolorpicker'; //選擇文字顏色(拾色器)
    $buttons[] = 'backcolorpicker'; //選擇背景顏色(拾色器)
    $buttons[] = 'spellchecker';    //切換拼寫(xiě)檢查器狀態(tài)

    return $buttons;
}

/*
 * TinyMCE編輯器增強(qiáng):增加中文字體
 */
add_filter('tiny_mce_before_init', 'custum_fontfamily');
function custum_fontfamily($initArray){
    $initArray['font_formats'] = "微軟雅黑='微軟雅黑';宋體='宋體';黑體='黑體';仿宋='仿宋';楷體='楷體';隸書(shū)='隸書(shū)';幼圓='幼圓';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings";
    return $initArray;
}


/*
 * 更改編輯器默認(rèn)視圖為HTML
 */
//add_filter('wp_default_editor', create_function('', 'return "html";'));

/*
 * 在 WordPress 編輯器中為自定義文章類型設(shè)置默認(rèn)內(nèi)容
 */
add_filter( 'default_content', 'my_editor_content', 10, 2 );
function my_editor_content( $content, $post ) {
    switch( $post->post_type ) {
        case 'sources':
            $content = 'your content';
            break;
        case 'stories':
            $content = 'your content';
            break;
        case 'pictures':
            $content = 'your content';
            break;
        default:
            $content = 'your default content';
            break;
    }
    return $content;
}

/*
 * 添加編輯器默認(rèn)內(nèi)容(此方法添加的內(nèi)容在發(fā)布文章時(shí)自動(dòng)添加在內(nèi)容的最后宴抚,在編輯的時(shí)候是看不見(jiàn)的)
 */
add_filter ('the_content', 'insertFootNote');
function insertFootNote($content) {
    if(!is_feed() && !is_home()) {
        $content.= "這里的預(yù)定義內(nèi)容在編輯器不可見(jiàn)";
    }
    return $content;
}

/*
 * 為編輯器添加更多的HTML標(biāo)簽
 */
add_filter('tiny_mce_before_init', 'fb_change_mce_options');
function fb_change_mce_options($initArray) {
    $ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]';  //注意:格式為“標(biāo)簽一[屬性一|屬性二],標(biāo)簽二[屬性一|屬性二|屬性三]”
    if ( isset( $initArray['extended_valid_elements'] ) ) {
        $initArray['extended_valid_elements'] .= ',' . $ext;
    } else {
        $initArray['extended_valid_elements'] = $ext;
    }
    return $initArray;
}

/*
 * 讓編輯器支持中文拼寫(xiě)檢查
 */
add_filter('tiny_mce_before_init', 'fb_mce_external_languages');
function fb_mce_external_languages($initArray){
    $initArray['spellchecker_languages'] = '+Chinese=zh,English=en';
    return $initArray;
}


/*
 * 更改后臺(tái)字體
 */
add_action('admin_head', 'Bing_admin_lettering');
function Bing_admin_lettering(){
    //echo '<style type="text/css">*{font-family:"Microsoft YaHei" !important;}</style>';//修改字體
}

/*
 * WordPress 后臺(tái)回復(fù)評(píng)論添加提交快捷鍵[Ctrl+Enter]
 */
add_action('admin_footer', 'Bing_admin_comment_ctrlenter');
function Bing_admin_comment_ctrlenter(){
    echo '<script type="text/javascript">
        jQuery(document).ready(function($){
            $("textarea").keypress(function(e){
                if(e.ctrlKey&&e.which==13||e.which==10){
                    $("#replybtn").click();
                }
            });
        });
    </script>';
};

/*
 * WordPress 讓后臺(tái)用戶列表可以根據(jù)文章數(shù)進(jìn)行排序
 */
if ( ! class_exists('Sort_Users_By_Post_Count') ) {
    class Sort_Users_By_Post_Count {
        function Sort_Users_By_Post_Count() {
            // Make user table sortable by post count
            add_filter( 'manage_users_sortable_columns', array( $this, 'add_custom_user_sorts' ) );
        }
        /* Add sorting by post count to user page */
        function add_custom_user_sorts( $columns ) {
            $columns['posts'] = 'post_count';
            return $columns;
        }
    }
    $Sort_Users_By_Post_Count = new Sort_Users_By_Post_Count();
}

/*
 * WordPress 4.3+ 默認(rèn)開(kāi)啟頁(yè)面的評(píng)論功能
 */
add_filter( 'get_default_comment_status', 'wp33516_open_comments_for_pages', 10, 3 );
function wp33516_open_comments_for_pages( $status, $post_type, $comment_type ) {
    if ( 'page' === $post_type ) {
        $status = 'open';
    }
    return $status;
}

/*
 * 將WordPress后臺(tái)的open-sans字體加載源從Google Fonts換為360 CDN
 */
add_action( 'init', 'wpdx_replace_open_sans' );
function wpdx_replace_open_sans() {
    wp_deregister_style('open-sans');
    wp_register_style( 'open-sans', '//fonts.useso.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600' );
    if(is_admin()) wp_enqueue_style( 'open-sans');
}

/*
 * WordPress 關(guān)閉 XML-RPC 的 pingback 端口
 */
add_filter( 'xmlrpc_methods', 'remove_xmlrpc_pingback_ping' );
function remove_xmlrpc_pingback_ping( $methods ) {
    unset( $methods['pingback.ping'] );
    return $methods;
}

/*
 * 禁用 WordPress 的 JSON REST API
 */
add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');

/*
 * 禁止WordPress壓縮JGP圖片質(zhì)量
 */
add_filter( 'jpg_quality', 'high_jpg_quality' );
function high_jpg_quality() {
    return 100;
}


/*
 * WordPress 隱藏特定插件的更新提示
 */
//add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' );
function filter_plugin_updates( $value ) {
    unset( $value->response['plugin-directory/plugin-file.php'] );
    return $value;
}


/*
 * 隱藏核心更新提示 WP 3.0+
 */
//add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) );

/*
 * 隱藏插件更新提示 WP 3.0+
 */
//remove_action( 'load-update-core.php', 'wp_update_plugins' );
//add_filter( 'pre_site_transient_update_plugins', create_function( '$b', "return null;" ) );

/*
 * 隱藏主題更新提示 WP 3.0+
 */
//remove_action( 'load-update-core.php', 'wp_update_themes' );
//add_filter( 'pre_site_transient_update_themes', create_function( '$c', "return null;" ) );

/*
 * 為新用戶預(yù)設(shè)默認(rèn)的后臺(tái)配色方案
 */
add_action('user_register', 'set_default_admin_color');
function set_default_admin_color($user_id) {
    $args = array(
        'ID' => $user_id,
        'admin_color' => 'sunrise'
    );
    wp_update_user( $args );
}

/*
 * 對(duì)非管理員移除配色方案設(shè)置選項(xiàng)
 */
if ( !current_user_can('manage_options') ){
    remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
}

/*
 * 移除 WordPress 儀表盤(pán)歡迎面板
 */
//remove_action('welcome_panel', 'wp_welcome_panel');

/*
 * 自定義 WordPress 儀表盤(pán)歡迎面板
 */
//add_action( 'welcome_panel', 'rc_my_welcome_panel' );
function rc_my_welcome_panel() {
    ?>
    <script type="text/javascript">
        /* 隱藏默認(rèn)的歡迎信息 */
        jQuery(document).ready( function($)
        {
            $('div.welcome-panel-content').hide();
        });
    </script>
    <!-- 添加自定義信息 -->
    <div class="custom-welcome-panel-content">
        <h2><?php _e( '歡迎使用WordPress!' ); ?></h2>
        <p class="about-description"><?php _e( '我們準(zhǔn)備了幾個(gè)鏈接供您開(kāi)始:' ); ?></p>
        <div class="welcome-panel-column-container">
            <div class="welcome-panel-column">
                <h3 style="font-weight: bold"><?php _e( "開(kāi)始使用" ); ?></h3>
                <a class="button button-primary button-hero load-customize hide-if-no-customize" ><?php _e( '聯(lián)系我們' ); ?></a>
                <p class="hide-if-no-customize"><?php printf( __( '或者 <a href="%s">設(shè)置網(wǎng)站</a>' ), admin_url( 'options-general.php' ) ); ?></p>
            </div>
            <div class="welcome-panel-column">
                <h4><?php _e( 'Next Steps' ); ?></h4>
                <ul>
                    <?php if ( 'page' == get_option( 'show_on_front' ) && ! get_option( 'page_for_posts' ) ) : ?>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
                    <?php elseif ( 'page' == get_option( 'show_on_front' ) ) : ?>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-edit-page">' . __( 'Edit your front page' ) . '</a>', get_edit_post_link( get_option( 'page_on_front' ) ) ); ?></li>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add additional pages' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Add a blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li>
                    <?php else : ?>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-write-blog">' . __( 'Write your first blog post' ) . '</a>', admin_url( 'post-new.php' ) ); ?></li>
                        <li><?php printf( '<a href="%s" class="welcome-icon welcome-add-page">' . __( 'Add an About page' ) . '</a>', admin_url( 'post-new.php?post_type=page' ) ); ?></li>
                    <?php endif; ?>
                    <li><?php printf( '<a href="%s" class="welcome-icon welcome-view-site">' . __( 'View your site' ) . '</a>', home_url( '/' ) ); ?></li>
                </ul>
            </div>
            <div class="welcome-panel-column welcome-panel-last">
                <h4><?php _e( 'More Actions' ); ?></h4>
                <ul>
                    <li><?php printf( '<div class="welcome-icon welcome-widgets-menus">' . __( 'Manage <a href="%1$s">widgets</a> or <a href="%2$s">menus</a>' ) . '</div>', admin_url( 'widgets.php' ), admin_url( 'nav-menus.php' ) ); ?></li>
                    <li><?php printf( '<a href="%s" class="welcome-icon welcome-comments">' . __( 'Turn comments on or off' ) . '</a>', admin_url( 'options-discussion.php' ) ); ?></li>
                    <li><?php printf( '<a href="%s" class="welcome-icon welcome-learn-more">' . __( 'Learn more about getting started' ) . '</a>', __( 'http://codex.wordpress.org/First_Steps_With_WordPress' ) ); ?></li>
                </ul>
            </div>
        </div>
        <div class="">
            <h3><?php _e( '關(guān)于我們' ); ?></h3>
            <!--<p class="about-description">延安安琪云信息科技有限公司</p>-->
            <p>延安安琪云信息科技有限公司成立于2017年10月23日践图,是陜北地區(qū)新興的互聯(lián)網(wǎng)綜合服務(wù)提供商掺冠。公司業(yè)務(wù)涉及網(wǎng)絡(luò)工程、軟件設(shè)計(jì)码党、電子商務(wù)德崭、電子政務(wù)、數(shù)據(jù)維護(hù)及品牌網(wǎng)站定制開(kāi)發(fā)揖盘。我們的目標(biāo)是成為廣大客戶值得信賴的互聯(lián)網(wǎng)綜合解決方案提供商眉厨!</p>
        </div>
    </div>
    <?php
}


/*
 * WordPress 限制非管理員用戶上傳圖片的最小寬度和高度
 */
add_action( 'admin_init', 'block_authors_from_uploading_small_images' );
function block_authors_from_uploading_small_images(){
    //除管理員以外,其他用戶都限制
    if( !current_user_can( 'manage_options') )
        add_filter( 'wp_handle_upload_prefilter', 'block_small_images_upload' );
}
function block_small_images_upload( $file ){
    // 檢測(cè)文件的類型是否是圖片
    $mimes = array( 'image/jpeg', 'image/png', 'image/gif' );
    // 如果不是圖片兽狭,直接返回文件
    if( !in_array( $file['type'], $mimes ) )
        return $file;

    $img = getimagesize( $file['tmp_name'] );
    // 設(shè)置最小寬度和高度
    $minimum = array( 'width' => 640, 'height' => 480 );

    if ( $img[0] < $minimum['width'] )
        $file['error'] =
            '圖片太小了憾股,最小寬度是 '
            . $minimum['width']
            . 'px,當(dāng)前上傳的圖片寬度是 '
            . $img[0] . 'px';

    elseif ( $img[1] < $minimum['height'] )
        $file['error'] =
            '圖片太小了箕慧,最小高度是 '
            . $minimum['height']
            . 'px服球,當(dāng)前上傳的圖片高度是 '
            . $img[1] . 'px';

    return $file;
}


/*
 * WordPress 后臺(tái)用戶列表顯示注冊(cè)時(shí)間
 */
add_filter( 'manage_users_columns', array('RRHE','registerdate'));
add_action( 'manage_users_custom_column',  array('RRHE','registerdate_columns'), 15, 3);
add_filter( 'manage_users_sortable_columns', array('RRHE','registerdate_column_sortable') );
add_filter( 'request', array('RRHE','registerdate_column_orderby') );
class RRHE {
    // Register the column - Registered
    public static function registerdate($columns) {
        $columns['registerdate'] = __('注冊(cè)時(shí)間', 'registerdate');
        return $columns;
    }

    // Display the column content
    public static function registerdate_columns( $value, $column_name, $user_id ) {
        if ( 'registerdate' != $column_name )
            return $value;
        $user = get_userdata( $user_id );
        $registerdate = get_date_from_gmt($user->user_registered);
        return $registerdate;
    }

    public static function registerdate_column_sortable($columns) {
        $custom = array(
            // meta column id => sortby value used in query
            'registerdate'    => 'registered',
        );
        return wp_parse_args($custom, $columns);
    }

    public static function registerdate_column_orderby( $vars ) {
        if ( isset( $vars['orderby'] ) && 'registerdate' == $vars['orderby'] ) {
            $vars = array_merge( $vars, array(
                'meta_key' => 'registerdate',
                'orderby' => 'meta_value'
            ) );
        }
        return $vars;
    }

}


/*
 * 在WordPress插件管理界面隱藏已啟用的插件(包括管理員)
 */
//add_filter( 'all_plugins', 'hide_plugins');
function hide_plugins($plugins)
{
    // 隱藏 你好,多莉 插件
    if(is_plugin_active('hello.php')) {
        unset( $plugins['hello.php'] );
    }
    // 隱藏 post series插件
    if(is_plugin_active('ankium/ankium.php')) {
        unset( $plugins['ankium/ankium.php'] );
    }
    return $plugins;
}

/*
 * 在WordPress插件管理界面隱藏已啟用的插件(除指定用戶)
 */
add_filter('all_plugins', 'filter_visible_plugins');
function filter_visible_plugins($plugins) {
    //添加插件的相對(duì)于 /wp-content/plugins/ 的路徑
    $pluginsToHide = array(
        'hello.php',
        'ankium/ankium.php'
    );
    //在這個(gè)例子中销钝,我們對(duì)所有用戶隱藏插件有咨,除了用戶 smith
    $currentUser = wp_get_current_user();
    $shouldHide = $currentUser->get('user_login') != 'ankium';

    if ( $shouldHide ) {
        foreach($pluginsToHide as $pluginFile) {
            unset($plugins[$pluginFile]);
        }
    }
    return $plugins;
}


/*
 * WordPress 移除插件列表所有已啟用插件的“編輯”和“停用”鏈接
 */
//add_filter( 'plugin_action_links', 'remove_all_plugin_actions', 10, 4 );
function remove_all_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
{
    // 移除所有“編輯”鏈接
    if ( isset( $actions['edit'] ) )
    {
        unset( $actions['edit'] );
    }
    // 移除插件的“停用”鏈接
    if( isset( $actions['deactivate'] ) )
    {
        unset( $actions['deactivate'] );
    }
    return $actions;
}


/*
 * WordPress 移除插件列表已啟用特定插件的“編輯”和“停用”鏈接
 */
//add_filter( 'plugin_action_links', 'remove_plugin_actions', 10, 4 );
function remove_plugin_actions( $actions, $plugin_file, $plugin_data, $context )
{
    // 移除所有“編輯”鏈接
    if ( isset( $actions['edit'] ) )
    {
        unset( $actions['edit'] );
    }
    // 移除插件的“停用”鏈接
    if( isset( $actions['deactivate'] ) )
    {
        switch($plugin_file)
        {
            // 添加插件的主文件目錄
            case 'hello.php': // 注意結(jié)尾是英文冒號(hào)
                unset( $actions['deactivate'] );
                break;
        }
    }
    return $actions;
}


/*
 * WordPress 禁用自定義文章類型的可視化編輯器
 */
//add_filter( 'user_can_richedit', 'disable_wysiwyg_editor_for_cpt' );
function disable_wysiwyg_editor_for_cpt( $default ) {
    global $post;
    if ( get_post_type( $post ) == 'question') // 請(qǐng)修改 question 為你的文章類型
        return false;
    return $default;
}


/*
 * WordPress 儀表盤(pán)顯示待審核的文章列表
 */
add_action('wp_dashboard_setup', 'wpjam_modify_dashboard_widgets' );
function wpjam_modify_dashboard_widgets() {
    global $wp_meta_boxes;

    if(current_user_can('manage_options')){ //只有管理員才能看到
        add_meta_box( 'pending_posts_dashboard_widget', '待審文章', 'pending_posts_dashboard_widget_function','dashboard', 'normal', 'core' );
    }
}
function pending_posts_dashboard_widget_function() {
    global $wpdb;
    $pending_posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts}  WHERE post_status = 'pending' ORDER BY post_modified DESC");

    if($pending_posts){ //判斷是否有待審文章
        echo '<ul>';
        foreach ($pending_posts as $pending_post){
            echo '<li><a href="'.admin_url().'post.php?post='.$pending_post->ID.'&action=edit">'.$pending_post->post_title.'</a></li>';
        }
        echo '</ul>';
    }else echo '目前沒(méi)有待審文章';
}


/*
 * WordPress 儀表盤(pán)“近期評(píng)論”顯示完整評(píng)論內(nèi)容和格式
 */
//add_filter('comment_excerpt', 'full_comments_on_dashboard');
function full_comments_on_dashboard($excerpt) {
    global $comment;

    if ( !is_admin() )
        return $excerpt;

    $content = wpautop($comment->comment_content);
    $content = substr($content, 3, -5); // 移除第一個(gè) <p> 和最后一個(gè) </p>
    $content = str_replace('<p>', '<p style="display:block; margin:1em 0">', $content);

    return $content;
}


/*
 * WordPress 后臺(tái)文章列表根據(jù)文章?tīng)顟B(tài)添加不同背景色
 */
add_action('admin_footer','posts_status_color');
function posts_status_color(){
    ?>
    <style>
        .status-draft{background: #FCE3F2 !important;/*草稿*/}
        .status-pending{background: #87C5D6 !important;/*待審核*/}
        .status-publish{/* 已發(fā)布,使用默認(rèn)背景色蒸健,你也可以自己添加顏色 */}
        .status-future{background: #C6EBF5 !important;/*定時(shí)發(fā)布*/}
        .status-private{background:#F2D46F;/*私密日志*/}
        .post-password-required{background:#D874DE;/*密碼保護(hù)*/}
    </style>
    <?php
}


/*
 * 更改標(biāo)題輸入框提示文字
 */
add_filter( 'enter_title_here', 'change_default_title' );
function change_default_title( $title ){
    $screen = get_current_screen();

    if( 'post' == $screen->post_type ) {
        $title = '輸入文章標(biāo)題';
    } elseif ('page' == $screen->post_type) {
        $title = '輸入頁(yè)面標(biāo)題';
    } elseif ('book' == $screen->post_type) {
        $title = '輸入書(shū)籍標(biāo)題';
    }

    return $title;
}

/*
 * 讓W(xué)ordPress記住不同主題下所選擇的的頁(yè)面模板
 */
add_action( "updated_post_meta", "rmt_update_post_template_meta", 10, 4 );
add_action( "added_post_meta", "rmt_update_post_template_meta", 10, 4 );
function rmt_update_post_template_meta( $meta_id, $post_id, $meta_key, $meta_value ){

    if( '_wp_page_template' === $meta_key ){

        $theme = wp_get_theme();
        $name = $theme->template;
        if( $name ){
            update_post_meta( $post_id, '_wp_page_template_' . $name, $meta_value );
        }

    }

}
add_filter( 'get_post_metadata', 'rmt_get_post_template_meta', 10, 4 );
function rmt_get_post_template_meta( $value, $post_id, $meta_key, $single ){

    if( '_wp_page_template' === $meta_key ){

        $theme = wp_get_theme();
        $name = $theme->template;

        if( $name ){
            $template = get_post_meta( $post_id, '_wp_page_template_' . $name, $single );
            if( $template  && locate_template( $template ) ){
                $value = $template;
            }
        }

    }

    return $value;
}


/*
 * 在媒體庫(kù)顯示文件尺寸
 */
//add_filter('manage_upload_columns', 'size_column_register');
function size_column_register($columns) {
    $columns['dimensions'] = __('Dimensions');
    return $columns;
}
//add_action('manage_media_custom_column', 'size_column_display', 10, 2);
function size_column_display($column_name, $post_id) {
    if( 'dimensions' != $column_name || !wp_attachment_is_image($post_id))
        return;
    list($url, $width, $height) = wp_get_attachment_image_src($post_id, 'full');
    echo esc_html("{$width}×{$height}");
}

/*
 * 在媒體編輯頁(yè)面顯示文件大小
 */
//add_action( 'attachment_submitbox_misc_actions', 'mc_attachment_submitbox_filesize' );
function mc_attachment_submitbox_filesize() {
    $post = get_post();
    $filesize = @filesize( get_attached_file( $post->ID ) );

    if ( ! empty( $filesize ) && is_numeric( $filesize ) && $filesize > 0 ) : ?>
        <div class="misc-pub-section">
            <?php _e( '文件大小:' ); ?> <strong><?php echo size_format( $filesize ); ?></strong>
        </div>
    <?php
    endif;
}

/*
 * 讓W(xué)ordPress后臺(tái)用戶列表可以搜索名字座享、姓氏和公開(kāi)顯示名
 */
if (is_admin()) {//讓函數(shù)只應(yīng)用于WordPress后臺(tái)
    //通過(guò)鉤子掛載函數(shù)
    add_action('pre_user_query', 'wpdaxue_pre_user_query');
}
function wpdaxue_pre_user_query($user_search) {
    global $wpdb;
    $vars = $user_search->query_vars;
    if (!is_null($vars['search'])) {
        // 出于某種原因,搜索詞被星號(hào)包括似忧,刪除它們
        $search = preg_replace('/^\*/', '', $vars['search']);
        $search = preg_replace('/\*$/', '', $search);

        //搜索公開(kāi)顯示名
        if(!empty($search)){
            $user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE '%". $search . "%')";
        }
        //搜索名字和姓氏
        $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " .
            "{$wpdb->users}.ID=m1.user_id AND (m1.meta_key='first_name')";
        $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " .
            "{$wpdb->users}.ID=m2.user_id AND (m2.meta_key='last_name')";
        $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s'", "%{$search}%", "%$search%");
        $user_search->query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$names_where} OR ", $user_search->query_where);
    }
    return $user_search;
}

/*
 * 為WordPress后臺(tái)的文章渣叛、分類等顯示ID
 */
add_action('admin_init', 'ssid_add');
// 添加一個(gè)新的列 ID
function ssid_column($cols) {
    $cols['ssid'] = 'ID';
    return $cols;
}
// 顯示 ID
function ssid_value($column_name, $id) {
    if ($column_name == 'ssid')
        echo $id;
}
function ssid_return_value($value, $column_name, $id) {
    if ($column_name == 'ssid')
        $value = $id;
    return $value;
}
// 為 ID 這列添加css
function ssid_css() {
    ?>
    <style type="text/css">
        #ssid { width: 50px; } /* Simply Show IDs */
    </style>
    <?php
}
// 通過(guò)動(dòng)作/過(guò)濾器輸出各種表格和CSS
function ssid_add() {
    add_action('admin_head', 'ssid_css');

    add_filter('manage_posts_columns', 'ssid_column');
    add_action('manage_posts_custom_column', 'ssid_value', 10, 2);

    add_filter('manage_pages_columns', 'ssid_column');
    add_action('manage_pages_custom_column', 'ssid_value', 10, 2);

    add_filter('manage_media_columns', 'ssid_column');
    add_action('manage_media_custom_column', 'ssid_value', 10, 2);

    add_filter('manage_link-manager_columns', 'ssid_column');
    add_action('manage_link_custom_column', 'ssid_value', 10, 2);

    add_action('manage_edit-link-categories_columns', 'ssid_column');
    add_filter('manage_link_categories_custom_column', 'ssid_return_value', 10, 3);

    foreach ( get_taxonomies() as $taxonomy ) {
        add_action("manage_edit-${taxonomy}_columns", 'ssid_column');
        add_filter("manage_${taxonomy}_custom_column", 'ssid_return_value', 10, 3);
    }

    add_action('manage_users_columns', 'ssid_column');
    add_filter('manage_users_custom_column', 'ssid_return_value', 10, 3);

    add_action('manage_edit-comments_columns', 'ssid_column');
    add_action('manage_comments_custom_column', 'ssid_value', 10, 2);
}


/*
 * 為WordPress頁(yè)面添加標(biāo)簽和分類
 */

class PTCFP{

    function __construct(){
        add_action( 'init', array( $this, 'taxonomies_for_pages' ) );
        //確保這些查詢修改不會(huì)作用于管理后臺(tái),防止文章和頁(yè)面混雜
        if ( ! is_admin() ) {
            add_action( 'pre_get_posts', array( $this, 'category_archives' ) );
            add_action( 'pre_get_posts', array( $this, 'tags_archives' ) );
        }
    }

    //為“頁(yè)面”添加“標(biāo)簽”和“分類”
    function taxonomies_for_pages() {
        register_taxonomy_for_object_type( 'post_tag', 'page' );
        register_taxonomy_for_object_type( 'category', 'page' );
    }

    //在標(biāo)簽存檔中包含“頁(yè)面”
    function tags_archives( $wp_query ) {
        if ( $wp_query->get( 'tag' ) )
            $wp_query->set( 'post_type', 'any' );
    }

    //在分類存檔中包含“頁(yè)面”
    function category_archives( $wp_query ) {
        if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
            $wp_query->set( 'post_type', 'any' );
    }

}

$ptcfp = new PTCFP();

/*
 * 限制文章標(biāo)題輸入字?jǐn)?shù)
 */
//add_action( 'admin_head-post.php', 'title_count_js');
//add_action( 'admin_head-post-new.php', 'title_count_js');
function title_count_js(){
    echo '<script>jQuery(document).ready(function(){
    jQuery("#titlewrap").after("<div><small>標(biāo)題字?jǐn)?shù): </small><input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"title_counter\" readonly=\"\" style=\"background:#fff;\"> <small>最大長(zhǎng)度不得超過(guò) 46 個(gè)字</small></div>");
    jQuery("#title_counter").val(jQuery("#title").val().length);
    jQuery("#title").keyup( function() {
    jQuery("#title_counter").val(jQuery("#title").val().length);
    });
    jQuery("#titlewrap #title").keyup( function() {
    var $this = jQuery(this);
    if($this.val().length > 46)
    $this.val($this.val().substr(0, 46));
    });
});</script>';
}

/*
 * 自定義排序WordPress后臺(tái)管理菜單
 */
//add_filter('custom_menu_order', 'custom_menu_order');
//add_filter('menu_order', 'custom_menu_order');
function custom_menu_order($menu_ord) {
    if (!$menu_ord) return true;
    return array(
        'index.php', // “儀表盤(pán)”菜單
        'edit.php?post_type=question', // 自定義文章類型的菜單
        'edit-comments.php', //“評(píng)論”菜單
        'upload.php', //“多媒體”菜單
        'edit.php?post_type=cmp_slider', //自定義文章類型的菜單
        'plugins.php', //“插件”菜單
        'themes.php', //“主題”菜單
        'edit.php?post_type=page', // “頁(yè)面”菜單
        'edit.php', // “文章”菜單
    );
}

/*
 * 在WordPress儀表盤(pán)“概況”顯示自定義文章類型數(shù)據(jù)
 */
add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
function wph_right_now_content_table_end() {
    $args = array(
        'public' => true ,
        '_builtin' => false
    );
    $output = 'object';
    $operator = 'and';
    $post_types = get_post_types( $args , $output , $operator );
    foreach( $post_types as $post_type ) {
        $num_posts = wp_count_posts( $post_type->name );
        $num = number_format_i18n( $num_posts->publish );
        $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) );
        if ( current_user_can( 'edit_posts' ) ) {
            $num = "<a href='edit.php?post_type=$post_type->name'>$num</a>";
            $text = "<a href='edit.php?post_type=$post_type->name'>$text</a>";
        }
        echo '<tr><td class="first num b b-' . $post_type->name . '">' . $num . '</td>';
        echo '<td class="text t ' . $post_type->name . '">' . $text . '</td></tr>';
    }
    $taxonomies = get_taxonomies( $args , $output , $operator );
    foreach( $taxonomies as $taxonomy ) {
        $num_terms  = wp_count_terms( $taxonomy->name );
        $num = number_format_i18n( $num_terms );
        $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms ));
        if ( current_user_can( 'manage_categories' ) ) {
            $num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>";
            $text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>";
        }
        echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>';
        echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>';
    }
}

/*
 * 儀表盤(pán)[活動(dòng)]小工具輸出自定義文章類型
 */
if ( is_admin() ) {
    add_filter( 'dashboard_recent_posts_query_args', 'wpdx_add_cpt_to_dashboard_activity' );
    function wpdx_add_cpt_to_dashboard_activity( $query ) {
        // 如果你要顯示所有文章類型盯捌,就刪除下行的 //淳衙,并在 11 行前面添加 //
        // $post_types = get_post_types();
        // 如果你僅僅希望顯示指定的文章類型,可以修改下行的數(shù)組內(nèi)容饺著,并確保上行前面添加 //
        $post_types = ['post', 'download'];
        if ( is_array( $query['post_type'] ) ) {
            $query['post_type'] = $post_types;
        } else {
            $temp = $post_types;
            $query['post_type'] = $temp;
        }
        return $query;
    }
}

/*
 * 顯示所有設(shè)置菜單
 */
add_action('admin_menu', 'all_settings_link');
function all_settings_link() {
    add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}

/*
 * 在WordPress后臺(tái)文章編輯器的上方或下方添加提示內(nèi)容
 */
add_action( 'edit_form_after_title', 'below_the_title' );
function below_the_title() {
    echo '<h3>在編輯器上方添加的提示內(nèi)容</h3>';
}
add_action( 'edit_form_after_editor', 'below_the_editor' );
function below_the_editor() {
    echo '<h4>在編輯器下方添加的提示內(nèi)容</h4>';
}

/*
 * 在后臺(tái)頁(yè)面管理列表中隱藏特定的頁(yè)面
 */
add_action( 'pre_get_posts' ,'exclude_this_page' );
function exclude_this_page( $query ) {
    if( !is_admin() )
        return $query;
    global $pagenow;
    if( 'edit.php' == $pagenow && ( get_query_var('post_type') && 'page' == get_query_var('post_type') ) )
        $query->set( 'post__not_in', array(23,28,30) ); // 頁(yè)面的ID
    return $query;
}

/*
 * 修改 WordPress 發(fā)送郵件的默認(rèn)郵箱和發(fā)件人
 */
add_filter('wp_mail_from_name', 'new_from_name');
add_filter('wp_mail_from', 'new_from_email');
function new_from_name($email){//默認(rèn)發(fā)件人
    $wp_from_name = get_option('blogname');
    return $wp_from_name;
}
function new_from_email($email) {//默認(rèn)發(fā)件箱
    $wp_from_email = get_option('admin_email');
    return $wp_from_email;
}

/*
 * WordPress儀表盤(pán)添加自定義Feed訂閱
 */
add_action('wp_dashboard_setup', 'ankium_add_dashboard_widgets' );
function dashboard_custom_feed_output() {
    echo '<div class="rss-widget">';
    wp_widget_rss_output(array(
        'url' => 'http://www.ankium.com/feed/', //rss地址
        'title' => '查看安琪云的最新內(nèi)容',
        'items' => 10,         //顯示篇數(shù)
        'show_summary' => 0,  //是否顯示摘要箫攀,1為顯示
        'show_author' => 0,   //是否顯示作者,1為顯示
        'show_date' => 1  )); //是否顯示日期
    echo '</div>';
}
function ankium_add_dashboard_widgets() {
    wp_add_dashboard_widget('example_dashboard_widget', '安琪云', 'dashboard_custom_feed_output');
}

/*
 * 自定義WordPress圖片附件的默認(rèn)鏈接方式(’none’,’file’,’post’)
 */
update_option('image_default_link_type', 'file');

/*
 * 關(guān)閉WordPress的XML-RPC離線發(fā)布功能
 */
add_filter('xmlrpc_enabled', '__return_false');

/*
 * 恢復(fù)WordPress默認(rèn)上傳路徑和生成文件的URL地址
 */
if(get_option('upload_path')=='wp-content/uploads' || get_option('upload_path')==null) {
    update_option('upload_path',WP_CONTENT_DIR.'/uploads');
}

/*
 * 自定義WordPress媒體文件的上傳路徑和生成文件的URL地址
 */
//add_filter( 'upload_dir', 'wpjam_custom_upload_dir' );
function wpjam_custom_upload_dir( $uploads ) {
    $upload_path = '';
    $upload_url_path = '';

    if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
        $uploads['basedir']  = WP_CONTENT_DIR . '/uploads';
    } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
        $uploads['basedir'] = path_join( ABSPATH, $upload_path );
    } else {
        $uploads['basedir'] = $upload_path;
    }

    $uploads['path'] = $uploads['basedir'].$uploads['subdir'];

    if ( $upload_url_path ) {
        $uploads['baseurl'] = $upload_url_path;
        $uploads['url'] = $uploads['baseurl'].$uploads['subdir'];
    }
    return $uploads;
}

/*
 * WordPress 后臺(tái)管理員免密一鍵切換其他賬號(hào)登錄
 */
add_filter('user_row_actions', 'wpdx_user_switch_action', 10, 2);
function wpdx_user_switch_action($actions, $user){
    $capability = (is_multisite())?'manage_site':'manage_options';
    if(current_user_can($capability)){
        $actions['login_as'] = '<a title="以此身份登錄" href="'.wp_nonce_url("users.php?action=login_as&users=$user->ID", 'bulk-users').'">以此身份登錄</a>';
    }
    return $actions;
}
add_filter('handle_bulk_actions-users','wpdx_handle_user_switch_action', 10, 3);
function wpdx_handle_user_switch_action($sendback, $action, $user_ids){
    if($action == 'login_as'){
        wp_set_auth_cookie($user_ids, true);
        wp_set_current_user($user_ids);
    }
    return admin_url();
}

/*
 * WordPress自定義文章作者名稱
 */
add_action('post_submitbox_misc_actions', 'cus_author_createCustomField');
add_action('save_post', 'cus_author_saveCustomField');
add_filter('the_author','cus_author_the_author');
/** 創(chuàng)建一個(gè)checkBox */
function cus_author_createCustomField() {
    $post_id = get_the_ID();
    if (get_post_type($post_id) != 'post') {
        return;
    }
    /*
     * 提取現(xiàn)有的值
     * @var boolean
     */
    $value = get_post_meta($post_id, '_custom_author_name', true);
    /*
     * 添加 nonce 安全處理
     */
    wp_nonce_field('custom_author_nonce' , 'custom_author_nonce');
    ?>
    <div class="misc-pub-section misc-pub-section-last dashicons-before dashicons-admin-users">
        <label><b>作者:</b><input type="text" value="<?php echo $value ?>" name="_custom_author_name" /></label>
    </div>
    <?php
}
//保存配置信息 $post_id 文章的ID
function cus_author_saveCustomField($post_id) {
    //自動(dòng)保存不處理
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    //信息不正確不處理
    if (
        !isset($_POST['custom_author_nonce']) ||
        !wp_verify_nonce($_POST['custom_author_nonce'], 'custom_author_nonce')
    ) {
        return;
    }
    //用戶無(wú)權(quán)編輯文章不處理
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    //存在此項(xiàng)目就更新
    if (isset($_POST['_custom_author_name'])) {
        update_post_meta($post_id, '_custom_author_name', sanitize_text_field($_POST['_custom_author_name']));
    } else {
        //不存在就刪除
        delete_post_meta($post_id, '_custom_author_name');
    }
}
function cus_author_the_author($author){
    $custom_author = get_post_meta(get_the_ID(), '_custom_author_name');
    if ($custom_author) {
        return $custom_author[0];
    } else {
        return $author;
    }
}

/*
 * 四合一簡(jiǎn)化 WordPress 后臺(tái)用戶個(gè)人信息姓名昵稱設(shè)置
 */
add_action('show_user_profile','wpjam_edit_user_profile');
add_action('edit_user_profile','wpjam_edit_user_profile');
function wpjam_edit_user_profile($user){
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('#first_name').parent().parent().hide();
            $('#last_name').parent().parent().hide();
            $('#display_name').parent().parent().hide();
            $('.show-admin-bar').hide();
        });
    </script>
    <?php
}
//更新時(shí)候幼衰,強(qiáng)制設(shè)置顯示名稱為昵稱
add_action('personal_options_update','wpjam_edit_user_profile_update');
add_action('edit_user_profile_update','wpjam_edit_user_profile_update');
function wpjam_edit_user_profile_update($user_id){
    if (!current_user_can('edit_user', $user_id))
        return false;
    $user = get_userdata($user_id);
    $_POST['nickname'] = ($_POST['nickname'])?:$user->user_login;
    $_POST['display_name']  = $_POST['nickname'];
    $_POST['first_name']    = '';
    $_POST['last_name']     = '';
}

/*
 * 禁用 WordPress 4.7 新增的PDF縮略圖預(yù)覽功能
 */
add_filter('fallback_intermediate_image_sizes', 'wpb_disable_pdf_previews');
function wpb_disable_pdf_previews() {
    $fallbacksizes = array();
    return $fallbacksizes;
}

/**
 * 新文章自動(dòng)使用ID作為別名
 * 作用:即使你設(shè)置固定連接結(jié)構(gòu)為 %postname% 靴跛,仍舊自動(dòng)生成 ID 結(jié)構(gòu)的鏈接
 */
add_action( 'save_post', 'using_id_as_slug', 10, 2 );
function using_id_as_slug($post_id, $post){
    global $post_type;
    if($post_type=='post'){ //只對(duì)文章生效
        // 如果是文章的版本,不生效
        if (wp_is_post_revision($post_id))
            return false;
        // 取消掛載該函數(shù)渡嚣,防止無(wú)限循環(huán)
        remove_action('save_post', 'using_id_as_slug' );
        // 使用文章ID作為文章的別名
        wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
        // 重新掛載該函數(shù)
        add_action('save_post', 'using_id_as_slug' );
    }
}

//根據(jù)上傳時(shí)間重命名文件
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' );
function custom_upload_filter( $file ){
    $info = pathinfo($file['name']);
    $ext = $info['extension'];
    $filedate = date('YmdHis').rand(10,99);//為了避免時(shí)間重復(fù)梢睛,再加一段2位的隨機(jī)數(shù)
    $file['name'] = $filedate.'.'.$ext;
    return $file;
}


//自動(dòng)調(diào)用媒體庫(kù)中的圖片作為縮略圖
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');
function wpforce_featured() {
    global $post;
    $already_has_thumb = has_post_thumbnail($post->ID);
    if (!$already_has_thumb)  {
       $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
           foreach ($attached_image as $attachment_id => $attachment) {
              set_post_thumbnail($post->ID, $attachment_id);
            }
        } else {
            set_post_thumbnail($post->ID, '10181');
        }
    }
}  //end function

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末肥印,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子绝葡,更是在濱河造成了極大的恐慌深碱,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,324評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件藏畅,死亡現(xiàn)場(chǎng)離奇詭異敷硅,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)墓赴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,356評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門竞膳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人诫硕,你說(shuō)我怎么就攤上這事】睿” “怎么了章办?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,328評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)滨彻。 經(jīng)常有香客問(wèn)我藕届,道長(zhǎng),這世上最難降的妖魔是什么亭饵? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,147評(píng)論 1 292
  • 正文 為了忘掉前任休偶,我火速辦了婚禮,結(jié)果婚禮上辜羊,老公的妹妹穿的比我還像新娘踏兜。我一直安慰自己,他們只是感情好八秃,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,160評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布碱妆。 她就那樣靜靜地躺著,像睡著了一般昔驱。 火紅的嫁衣襯著肌膚如雪疹尾。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,115評(píng)論 1 296
  • 那天骤肛,我揣著相機(jī)與錄音纳本,去河邊找鬼。 笑死腋颠,一個(gè)胖子當(dāng)著我的面吹牛繁成,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播秕豫,決...
    沈念sama閱讀 40,025評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼朴艰,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼观蓄!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起祠墅,我...
    開(kāi)封第一講書(shū)人閱讀 38,867評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤侮穿,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后毁嗦,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體亲茅,經(jīng)...
    沈念sama閱讀 45,307評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,528評(píng)論 2 332
  • 正文 我和宋清朗相戀三年狗准,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了克锣。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,688評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腔长,死狀恐怖袭祟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情捞附,我是刑警寧澤巾乳,帶...
    沈念sama閱讀 35,409評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站鸟召,受9級(jí)特大地震影響胆绊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜欧募,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,001評(píng)論 3 325
  • 文/蒙蒙 一压状、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧跟继,春花似錦种冬、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,657評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至剩盒,卻和暖如春谷婆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背辽聊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,811評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工纪挎, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人跟匆。 一個(gè)月前我還...
    沈念sama閱讀 47,685評(píng)論 2 368
  • 正文 我出身青樓异袄,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親玛臂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子烤蜕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,573評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容