很全面的WordPress模板下”functions.php”函數集錦(大全)
[重要通告]如您遇疑難雜癥,本站支持知識付費業務,掃右邊二維碼加博主微信,可節省您寶貴時間哦!
經常說到wordpress,因為大家也是對做站用wordpress也越來越多,其中wordpress中“functions.php”文件是其重要的組成部分通過它,可以做到插件實現的功能,也就是免插件如何如何~通過下面的這些代碼來增強優化自己的網站是必要的哦,具體請看;
1、在header中添加RSS鏈接
// add feed links to header if (function_exists('automatic_feed_links')) { automatic_feed_links(); } else { return; }
2、加載自定義jQuery庫
// smart jquery inclusion if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.useso.com/ajax/libs/jquery/1/jquery.min.js"), false); wp_enqueue_script('jquery'); }
3、適應層疊評論
// enable threaded comments function enable_threaded_comments(){ if (!is_admin()) { if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) wp_enqueue_script('comment-reply'); } } add_action('get_header', 'enable_threaded_comments');
4、去除多余頭部信息代碼
// remove junk from head remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wp_generator'); remove_action('wp_head', 'feed_links', 2); remove_action('wp_head', 'index_rel_link'); remove_action('wp_head', 'wlwmanifest_link'); remove_action('wp_head', 'feed_links_extra', 3); remove_action('wp_head', 'start_post_rel_link', 10, 0); remove_action('wp_head', 'parent_post_rel_link', 10, 0); remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);
5、在footer添加統計代碼
// add tongji to footer function add_tongji() { echo '<script src="統計代碼" type="text/javascript"></script>'; } add_action('wp_footer', 'add_tongji');
6、自定義摘要長度
// custom excerpt length function custom_excerpt_length($length) { return 80; } add_filter('excerpt_length', 'custom_excerpt_length');
7、自定義摘要結尾的截斷
// custom excerpt ellipses for 2.9+ function custom_excerpt_more($more) { return '...'; } add_filter('excerpt_more', 'custom_excerpt_more');
8、自定義摘要結尾的繼續閱讀
// no more jumping for read more link function no_more_jumping($post) { return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'閱讀更多'.'</a>'; } add_filter('excerpt_more', 'no_more_jumping');
9、給WordPress添加全站圖標favicon
// add a favicon to your function blog_favicon() { echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />'; } add_action('wp_head', 'blog_favicon');
10、給WordPress后臺添加圖標favicon
// add a favicon for your admin function admin_favicon() { echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('stylesheet_directory').'/img/favicon.png" />'; } add_action('admin_head', 'admin_favicon');
注:這里的網站圖標只有在后臺才能看到,前臺不受影響,前后后兩種圖標。
11、自定義登陸頁面logo
// custom admin login logo function custom_login_logo() { echo '<style type="text/css"> h1 a { background-image: url('.get_bloginfo('template_directory').'/img/login-logo.png) !important; } </style>'; } add_action('login_head', 'custom_login_logo');
在wordpress主題“img”文件夾中甩一個LOGO圖標進去命名“login-logo.png”即可。
12、禁用小工具
// disable all widget areas function disable_all_widgets($sidebars_widgets) { //if (is_home()) $sidebars_widgets = array(false); return $sidebars_widgets; } add_filter('sidebars_widgets', 'disable_all_widgets');
13、取消后臺的更新提示
// kill the admin nag if (!current_user_can('edit_users')) { add_action('init', create_function('$a', "remove_action('init', 'wp_version_check');"), 2); add_filter('pre_option_update_core', create_function('$a', "return null;")); }
14、在body_class 和 post_class中包含分類id
// category id in body and post class function category_id_class($classes) { global $post; foreach((get_the_category($post->ID)) as $category) $classes [] = 'cat-' . $category->cat_ID . '-id'; return $classes; } add_filter('post_class', 'category_id_class'); add_filter('body_class', 'category_id_class');
15、獲取第一個分類id
// get the first category id function get_first_category_ID() { $category = get_the_category(); return $category[0]->cat_ID; }
16、在面額文章以及feed之后插入自定義內容
// add custom content to feeds and posts function add_custom_content($content) { if(!is_home()) { $content .= '<p>This article is copyright ? '.date('Y').' '.bloginfo('name').'</p>'; } return $content; } add_filter('the_excerpt_rss', 'add_custom_content'); add_filter('the_content', 'add_custom_content');
17、隱藏WordPress版本號
// remove version info from head and feeds function complete_version_removal() { return ''; } add_filter('the_generator', 'complete_version_removal');
18、自定義后臺左下角的文字
// customize admin footer text function custom_admin_footer() { echo '么么噠'; } add_filter('admin_footer_text', 'custom_admin_footer');
19、用戶描述里面使用HTML代碼
// enable html markup in user profiles remove_filter('pre_user_description', 'wp_filter_kses');
20、文章發布之后延遲rss的推送
// delay feed update function publish_later_on_feed($where) { global $wpdb; if (is_feed()) { // timestamp in WP-format $now = gmdate('Y-m-d H:i:s'); // value for wait; + device $wait = '5'; // integer // http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff $device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR // add SQL-sytax to default $where $where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait "; } return $where; } add_filter('posts_where', 'publish_later_on_feed');
21、后臺菜單添加所有設置菜單
// admin link for all settings function all_settings_link() { add_options_page(__('全部設置'), __('全部設置'), 'administrator', 'options.php'); } add_action('admin_menu', 'all_settings_link');
這個頁面是wordpress的全部數據表單,危險區域慎動!
22、移除評論中的nofollow屬性
// remove nofollow from comments function xwp_dofollow($str) { $str = preg_replace( '~<a ([^>]*)\s*(["|\']{1}\w*)\s*nofollow([^>]*)>~U', '<a ${1}${2}${3}>', $str); return str_replace(array(' rel=""', " rel=''"), '', $str); } remove_filter('pre_comment_content', 'wp_rel_nofollow'); add_filter ('get_comment_author_link', 'xwp_dofollow'); add_filter ('post_comments_link', 'xwp_dofollow'); add_filter ('comment_reply_link', 'xwp_dofollow'); add_filter ('comment_text', 'xwp_dofollow');
23、給評論添加垃圾,刪除按鈕
// spam & delete links for all versions of wordpress function delete_comment_link($id) { if (current_user_can('edit_post')) { echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">刪除評論</a> '; echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">垃圾評論</a>'; } }
24、徹底禁用WordPress的rss功能
// disable all feeds function fb_disable_feed() { wp_die(__('<h1>本站不提供RSS閱讀服務,請<a href="'.get_bloginfo('url').'">點擊此處</a>返回首頁</h1>')); } add_action('do_feed', 'fb_disable_feed', 1); add_action('do_feed_rdf', 'fb_disable_feed', 1); add_action('do_feed_rss', 'fb_disable_feed', 1); add_action('do_feed_rss2', 'fb_disable_feed', 1); add_action('do_feed_atom', 'fb_disable_feed', 1);
25、自定義WordPress默認頭像
// customize default gravatars function custom_gravatars($avatar_defaults) { // change the default gravatar $customGravatar1 = get_bloginfo('template_directory').'/images/gravatar-01.png'; $avatar_defaults[$customGravatar1] = 'Default'; // add a custom user gravatar $customGravatar2 = get_bloginfo('template_directory').'/images/gravatar-02.png'; $avatar_defaults[$customGravatar2] = 'Custom Gravatar'; // add another custom gravatar $customGravatar3 = get_bloginfo('template_directory').'/images/gravatar-03.png'; $avatar_defaults[$customGravatar3] = 'Custom gravatar'; return $avatar_defaults; } add_filter('avatar_defaults', 'custom_gravatars');
26、轉換評論中的HTML實體
// escape html entities in comments function encode_code_in_comment($source) { $encoded = preg_replace_callback('/<code>(.*?)<\/code>/ims', create_function('$matches', '$matches[1] = preg_replace(array("/^[\r|\n]+/i", "/[\r|\n]+$/i"), "", $matches[1]); return "<code>" . htmlentities($matches[1]) . "</"."code>";'), $source); if ($encoded) return $encoded; else return $source; } add_filter('pre_comment_content', 'encode_code_in_comment');
27、在upload文件夾下新建一個目錄
function my_upload_dir() { $upload = wp_upload_dir(); $upload_dir = $upload['basedir']; $upload_dir = $upload_dir . '/mypluginfiles'; if (!is_dir($upload_dir)) { mkdir($upload_dir, 448); } } register_activation_hook(__FILE__, 'my_upload_dir');
28、去除文章圖片自動添加尺寸的問題
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 ); add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 ); function remove_width_attribute( $html ) { $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); return $html; }
29、WordPress后臺自定義樣式
add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo '<style> body, td, textarea, input, select { font-family: "Lucida Grande"; font-size: 12px; } </style>'; }
30、使用短代碼使用bloginfo函數
function digwp_bloginfo_shortcode( $atts ) { extract(shortcode_atts(array( 'key' => '', ), $atts)); return get_bloginfo($key); } add_shortcode('bloginfo', 'digwp_bloginfo_shortcode');
31、使用短代碼防止WordPress自動格式化
function my_formatter($content) { $new_content = ''; $pattern_full = '{(\[raw\].*?\[/raw\])}is'; $pattern_contents = '{\[raw\](.*?)\[/raw\]}is'; $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($pieces as $piece) { if (preg_match($pattern_contents, $piece, $matches)) { $new_content .= $matches[1]; } else { $new_content .= wptexturize(wpautop($piece)); } } return $new_content; } remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); add_filter('the_content', 'my_formatter', 99);
使用方法:[raw]Unformatted code[/raw]
32、通過ID獲取文章內容
function get_the_content_by_id($post_id) { $page_data = get_page($post_id); if ($page_data) { return $page_data->post_content; } else return false; }
33、在控制面板創建一個小工具
// Function that outputs the contents of the dashboard widget function dashboard_widget_function( $post, $callback_args ) { echo "Hello World, this is my first Dashboard Widget!"; } // Function used in the action hook function add_dashboard_widgets() { wp_add_dashboard_widget('dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function'); } // Register the new dashboard widget with the 'wp_dashboard_setup' action add_action('wp_dashboard_setup', 'add_dashboard_widgets' );
34、控制面板創建一個表格小工具
// Function that outputs the contents of the dashboard widget function dashboard_widget_function( $post, $callback_args ) { //Put your all code here which generate the output of summary box $site_users = get_users(); foreach ( $site_users as $user ) { echo $user->display_name; echo $user->roles[0]; echo get_edit_user_link( $user->ID ); } }
35、更換控制面板logo
//hook the administrative header output add_action('admin_head', 'my_custom_logo'); function my_custom_logo() { echo ' <style type="text/css"> #header-logo {background-image: url('.get_bloginfo('template_directory').'/images/custom-logo.gif) !important; } </style> '; }
36、禁用可視化編輯器自動補全標簽
//disable wpautop filter remove_filter ('the_content', 'wpautop');
37、增加減少WordPress用戶角色
function wps_add_role() { add_role( 'manager', 'Manager', array( 'read', 'edit_posts', 'delete_posts', ) ); } add_action( 'init', 'wps_add_role' ); function wps_remove_role() { remove_role( 'editor' ); remove_role( 'author' ); remove_role( 'contributor' ); remove_role( 'subscriber' ); } add_action( 'init', 'wps_remove_role' );
38、添加圖片附件上傳時候的默認項
function wps_attachment_display_settings() { update_option( 'image_default_align', 'center' ); update_option( 'image_default_link_type', 'none' ); update_option( 'image_default_size', 'large' ); } add_action( 'after_setup_theme', 'wps_attachment_display_settings' );
39、圖片上傳時候添加自定義尺寸
if ( function_exists( 'add_image_size' ) ) { add_image_size( 'new-size', 300, 100, true ); //(cropped) } add_filter('image_size_names_choose', 'my_image_sizes'); function my_image_sizes($sizes) { $addsizes = array( "new-size" => __( "自定義尺寸") ); $newsizes = array_merge($sizes, $addsizes); return $newsizes; }
40、更換WordPress默認的用戶角色名
function wps_change_role_name() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $wp_roles->roles['contributor']['name'] = 'Owner'; $wp_roles->role_names['contributor'] = 'Owner'; } add_action('init', 'wps_change_role_name');
41、主題激活后自動創建頁面
if (isset($_GET['activated']) && is_admin()){ $new_page_title = 'This is the page title'; $new_page_content = 'This is the page content'; $new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template. //don't change the code bellow, unless you know what you're doing $page_check = get_page_by_title($new_page_title); $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, ); if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } } }
42、非管理員不得訪問后臺
add_action( 'init', 'blockusers_wps_init' ); function blockusers_wps_init() { if ( is_admin() && ! current_user_can( 'administrator' ) ) { wp_redirect( home_url() );//滾回首頁吧 exit; } }
43、用戶注冊成功后跳轉
function wps_registration_redirect(){ return home_url( '/finished/' ); } add_filter( 'registration_redirect', 'wps_registration_redirect' );
44、給自定義文章添加概覽計數
add_filter( 'dashboard_glance_items', 'custom_glance_items', 10, 1 ); function custom_glance_items( $items = array() ) { $post_types = array( 'post_type_1', 'post_type_2' ); foreach( $post_types as $type ) { if( ! post_type_exists( $type ) ) continue; $num_posts = wp_count_posts( $type ); if( $num_posts ) { $published = intval( $num_posts->publish ); $post_type = get_post_type_object( $type ); $text = _n( '%s ' . $post_type->labels->singular_name, '%s ' . $post_type->labels->name, $published, 'your_textdomain' ); $text = sprintf( $text, number_format_i18n( $published ) ); if ( current_user_can( $post_type->cap->edit_posts ) ) { $items[] = sprintf( '%2$s', $type, $text ) . "\n"; } else { $items[] = sprintf( '%2$s', $type, $text ) . "\n"; } } } return $items; } 美美嗒~ #dashboard_right_now a.post_type-count:before, #dashboard_right_now span.post_type-count:before { content: "\f109"; }
45、給可視化編輯器添加短代碼
add_action('media_buttons','add_sc_select',11); function add_sc_select(){ echo ' <select id="sc_select"> <option>短代碼</option> <option value="[html][/html]">[html]</option> <option value="[css][/css]">[css[</option> <option value="[javascript][/javascript]">[javascript]</option> </select>'; } add_action('admin_head', 'button_js'); function button_js() { echo '<script type="text/javascript"> jQuery(document).ready(function(){ jQuery("#sc_select").change(function() { send_to_editor(jQuery("#sc_select :selected").val()); return false; }); }); </script>'; }
46、給文章添加特色圖才給發布,否則不給發
add_action('save_post', 'wpds_check_thumbnail'); add_action('admin_notices', 'wpds_thumbnail_error'); function wpds_check_thumbnail($post_id) { // change to any custom post type if(get_post_type($post_id) != 'post') return; if ( !has_post_thumbnail( $post_id ) ) { // set a transient to show the users an admin message set_transient( "has_post_thumbnail", "no" ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'wpds_check_thumbnail'); // update the post set it to draft wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'wpds_check_thumbnail'); } else { delete_transient( "has_post_thumbnail" ); } } function wpds_thumbnail_error() { // check if the transient is set, and display the error message if ( get_transient( "has_post_thumbnail" ) == "no" ) { echo "<div id='message' class='error'><p><strong>您必須選擇一個特色圖片,您的文章現已被保存,但是無法發布。</strong></p></div>"; delete_transient( "has_post_thumbnail" ); } }
47、要求評論字數的最小值
add_filter( 'preprocess_comment', 'minimal_comment_length' ); function minimal_comment_length( $commentdata ) { $minimalCommentLength = 20;//這里自己改 if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ){ wp_die( '評論最起碼要有 ' . $minimalCommentLength . ' 個字符哦.' ); } return $commentdata; }
48、用顏色區分后臺文章的狀態
add_action('admin_footer','posts_status_color'); function posts_status_color(){ ?> <style> .status-draft{background: #FCE3F2 !important;} .status-pending{background: #87C5D6 !important;} .status-publish{/* no background keep wp alternating colors */} .status-future{background: #C6EBF5 !important;} .status-private{background:#F2D46F;} </style> <?php }
49、給特定文章/頁面強制SSL瀏覽
function wps_force_ssl( $force_ssl, $post_id = 0, $url = '' ) { if ( $post_id == 25 ) { return true } return $force_ssl; } add_filter('force_ssl' , 'wps_force_ssl', 10, 3);
50、給后臺添加指引
add_action( 'admin_enqueue_scripts', 'my_admin_enqueue_scripts' ); function my_admin_enqueue_scripts() { wp_enqueue_style( 'wp-pointer' ); wp_enqueue_script( 'wp-pointer' ); add_action( 'admin_print_footer_scripts', 'my_admin_print_footer_scripts' ); } function my_admin_print_footer_scripts() { $pointer_content = '<h3>森林之家的通知</h3>'; $pointer_content .= '<p>這是一個通知</p>'; ?> <script type="text/javascript"> //<![CDATA[ jQuery(document).ready( function($) { $('#menu-appearance').pointer({ content: '<?php echo $pointer_content; ?>', position: 'left', close: function() { // Once the close button is hit } }).pointer('open'); }); //]]> </script> <?php }
51、給WordPress添加歡迎信息
<?php if( strpos($_SERVER[HTTP_REFERER], "baidu.com" ) == true ): ?> <div class="welcome-stumbleupon"> <p>歡迎來自百度的親們!</p> </div> <?php endif; ?>
注:此段是加在主題目錄下“header.php”文件中,樣式自己另行增加。
52、角色變換時候發送電子郵件
function user_role_update( $user_id, $new_role ) { $site_url = get_bloginfo('wpurl'); $user_info = get_userdata( $user_id ); $to = $user_info->user_email; $subject = "Role changed: ".$site_url.""; $message = "Hello " .$user_info->display_name . " 親,您在".$site_url.", 角色已經變為 " . $new_role; wp_mail($to, $subject, $message); } add_action( 'set_user_role', 'user_role_update', 10, 2);
53、短代碼添加一個網站的截圖
function wps_screenshot($atts, $content = null) { extract(shortcode_atts(array( "screenshot" => 'http://s.wordpress.com/mshots/v1/', "url" => 'http://', "alt" => 'screenshot', "width" => '400', "height" => '300' ), $atts)); return $screen = '<img src="' . $screenshot . '' . urlencode($url) . '?w=' . $width . '&h=' . $height . '" alt="' . $alt . '"/>'; } add_shortcode("screenshot", "wps_screenshot");
用法:
[screenshot url=”http://0mbx6.cn” alt=”wordpress code snippets for your blog” width=”200″ height=”200″]
54、使用短代碼添加倒計時功能
function content_countdown($atts, $content = null){ extract(shortcode_atts(array( 'month' => '', 'day' => '', 'year' => '' ), $atts)); $remain = ceil((mktime( 0,0,0,(int)$month,(int)$day,(int)$year) - time())/86400); if( $remain > 1 ){ return $daysremain = "<div class=\"event\">Just <b>($remain)</b> days until content is available</div>"; }else if($remain == 1 ){ return $daysremain = "<div class=\"event\">Just <b>($remain)</b> day until content is available</div>"; }else{ return $content; } } add_shortcode('cdt', 'content_countdown');
使用:
[cdt month=”10″ day=”17″ year=”2011″]本次活動已過期,請下次再來!-老梁博客[/cdt]
55、強制控制面板顯示一列
function single_screen_columns( $columns ) { $columns['dashboard'] = 1; return $columns; } add_filter( 'screen_layout_columns', 'single_screen_columns' ); function single_screen_dashboard(){return 1;} add_filter( 'get_user_option_screen_layout_dashboard', 'single_screen_dashboard' );
56、讓登陸用戶自己選擇登陸后的跳轉
// Fields for redirect function custom_login_fields() { ?> <p> <label> <strong>Choose your location: </strong> <select name="login_location"> <option value="">Select …</option> <option value="<?php bloginfo('url'); ?>#banking">Banking</option> <option value="<?php bloginfo('url'); ?>#insurance">Insurance</option> <option value="<?php echo get_permalink(2); ?>">Securities</option> </select> </label> </p><br/> <?php } // Redirect function function location_redirect() { $location = $_POST['login_location']; wp_safe_redirect($location); exit(); } // Add fields to the login form add_action('login_form','custom_login_fields'); // Make sure the redirect happens only if your fields are submitted if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) add_filter('login_redirect', 'location_redirect', 10, 3);
問題未解決?付費解決問題加Q或微信 2589053300 (即Q號又微信號)右上方掃一掃可加博主微信
所寫所說,是心之所感,思之所悟,行之所得;文當無敷衍,落筆求簡潔。 以所舍,求所獲;有所依,方所成!