問題描述
請通過點擊問題或答案左側的向上箭頭來投票支持該問題及您認為有用的任何答案。
正如許多其他正在查看這篇文章的人一樣,我一直在閲讀各種博客,論壇和討論組,以學習和提高我的 WordPress 技能。在過去 12 個月中,我一直在使用我的 functions.php 文件代替我的插件替代代碼。雖然我完全同意插件在許多情況下非常有用,但我的經驗證明,儘管插件可能存在 90%的使用情況,但實際使用它可能會產生不必要的併發症和兼容性問題。此外,在很多情況下,這種插件添加了我不想要或不需要的菜單和其他管理元素。
我經常發現通過分析插件的代碼,我可以把我想要的代碼片斷,並將其硬編碼到我的 functions.php 中。這為我提供了我需要的確切功能,而不必包括不必要的元素。
所以,這個帖子的目的是我試圖讓你,讀者/管理員/開發人員與我和其他人分享你發現的有用的代碼位,並添加到您的主題的 function.php 文件以擴展或增強 WordPress,而不使用一個插件
當您在此提交答覆時,請各位代表一個標題,讓我們知道如果您知道與哪個版本的 WordPress 兼容,請附上您最感興趣的描述其功能的內容 (如適用),包括原始鏈接您發現信息的插件或源代碼。
我期待所有的回應,當然,當我找到他們的時候,當然會不斷添加自己的新發現。
最佳解決方案
啓用隱藏管理功能,顯示所有站點設置
測試:Wordpress 3.1 RC3
這個小代碼做的很好,它將為您的設置菜單添加一個附加選項,其中包含 「所有設置」 的鏈接,這將顯示您的數據庫中與 WordPress 站點相關的所有設置的完整列表。以下代碼只會使此鏈接對管理員用户可見,並將其隱藏給所有其他用户。
// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS
function all_settings_link() {
add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}
add_action('admin_menu', 'all_settings_link');
次佳解決方案
修改登錄徽標& 圖像 URL 鏈接
測試:WordPress 3.0.1
此代碼將允許您輕鬆修改 WordPress 登錄頁面徽標以及該徽標的 href 鏈接和標題文本。
add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
* Replaces the login header logo URL
*
* @param $url
*/
function namespace_login_headerurl( $url ) {
$url = home_url( '/' );
return $url;
}
add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
* Replaces the login header logo title
*
* @param $title
*/
function namespace_login_headertitle( $title ) {
$title = get_bloginfo( 'name' );
return $title;
}
add_action( 'login_head', 'namespace_login_style' );
/**
* Replaces the login header logo
*/
function namespace_login_style() {
echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}
編輯:如果要使用站點徽標替換登錄徽標,可以使用以下動態拉動該信息 (在 WP3.5 上測試):
function namespace_login_style() {
if( function_exists('get_custom_header') ){
$width = get_custom_header()->width;
$height = get_custom_header()->height;
} else {
$width = HEADER_IMAGE_WIDTH;
$height = HEADER_IMAGE_HEIGHT;
}
echo '<style>'.PHP_EOL;
echo '.login h1 a {'.PHP_EOL;
echo ' background-image: url( '; header_image(); echo ' ) !important; '.PHP_EOL;
echo ' width: '.$width.'px !important;'.PHP_EOL;
echo ' height: '.$height.'px !important;'.PHP_EOL;
echo ' background-size: '.$width.'px '.$height.'px !important;'.PHP_EOL;
echo '}'.PHP_EOL;
echo '</style>'.PHP_EOL;
}
第三種解決方案
刪除除 ADMIN 用户以外的所有用户的更新通知
測試:Wordpress 3.0.1
該代碼將確保在更新可用時,WordPress 不會通知”admin” 以外的用户。
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
global $user_login;
get_currentuserinfo();
if ($user_login !== "admin") { // change admin to the username that gets the updates
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
更改版本只顯示管理員用户的更新通知 (而不僅僅是用户’admin’):
// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
global $user_login;
get_currentuserinfo();
if (!current_user_can('update_plugins')) { // checks to see if current user can update plugins
add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
}
第四種方案
在搜索結果中包含自定義帖子類型。
// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); }
return $query;
}
add_filter( 'the_search_query', 'searchAll' );
默認情況下,將自定義帖子類型添加到您的站點主 RSS Feed 。
// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
if (isset($vars['feed']) && !isset($vars['post_type']))
$vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
return $vars;
}
add_filter( 'request', 'custom_feed_request' );
在 「Right Now」 管理控制枱小工具中包含自定義帖子類型
這將包括您的自定義帖子類型和在 「現在」 的儀錶板小工具中的每種類型的帖子計數。
// ADD CUSTOM POST TYPES TO THE 'RIGHT NOW' DASHBOARD WIDGET
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>';
}
}
add_action( 'right_now_content_table_end' , 'wph_right_now_content_table_end' );
第五種方案
從 Google CDN 加載 jQuery
測試:Wordpress 3.0.1
// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );
// register from google and for footer
function jquery_register() {
if ( !is_admin() ) {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', ( 'https://googleajax.admincdn.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
wp_enqueue_script( 'jquery' );
}
}
刪除 WordPress 版本信息的安全
測試:Wordpress 3.0.1
// remove version info from head and feeds
function complete_version_removal() {
return '';
}
add_filter('the_generator', 'complete_version_removal');
添加垃圾郵件刪除鏈接到前端的評論
測試:Wordpress 3.0.1
這使得通過添加垃圾郵件和刪除鏈接來管理來自前端的評論更容易。**
// 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.'">del</a> ';
echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
}
}
將公開發布延遲到 RSS Feed
測試:Wordpress 3.0.1
最後,我喜歡延遲發佈到我的 RSS Feed 10-15 分鐘,因為我總是發現我的文本中至少有一些錯誤。其他用途如果您希望內容在您的 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 = '10'; // 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');
第六種方案
WordPress 分析工具
我喜歡在一個單獨的文件中添加分析工具,然後在需要時從 functions.php 中包含:
<?php
if ( !defined('SAVEQUERIES') && isset($_GET['debug']) && $_GET['debug'] == 'sql' )
define('SAVEQUERIES', true);
if ( !function_exists('dump') ) :
/**
* dump()
*
* @param mixed $in
* @return mixed $in
**/
function dump($in = null) {
echo '<pre style="margin-left: 0px; margin-right: 0px; padding: 10px; border: solid 1px black; background-color: ghostwhite; color: black; text-align: left;">';
foreach ( func_get_args() as $var ) {
echo "n";
if ( is_string($var) ) {
echo "$varn";
} else {
var_dump($var);
}
}
echo '</pre>' . "n";
return $in;
} # dump()
endif;
/**
* add_stop()
*
* @param mixed $in
* @param string $where
* @return mixed $in
**/
function add_stop($in = null, $where = null) {
global $sem_stops;
global $wp_object_cache;
$queries = get_num_queries();
$milliseconds = timer_stop() * 1000;
$out = "$queries queries - {$milliseconds}ms";
if ( function_exists('memory_get_usage') ) {
$memory = number_format(memory_get_usage() / ( 1024 * 1024 ), 1);
$out .= " - {$memory}MB";
}
$out .= " - $wp_object_cache->cache_hits cache hits / " . ( $wp_object_cache->cache_hits + $wp_object_cache->cache_misses );
if ( $where ) {
$sem_stops[$where] = $out;
} else {
dump($out);
}
return $in;
} # add_stop()
/**
* dump_stops()
*
* @param mixed $in
* @return mixed $in
**/
function dump_stops($in = null) {
if ( $_POST )
return $in;
global $sem_stops;
global $wp_object_cache;
$stops = '';
foreach ( $sem_stops as $where => $stop )
$stops .= "$where: $stopn";
dump("n" . trim($stops) . "n");
if ( defined('SAVEQUERIES') && $_GET['debug'] == 'sql' ) {
global $wpdb;
foreach ( $wpdb->queries as $key => $data ) {
$query = rtrim($data[0]);
$duration = number_format($data[1] * 1000, 1) . 'ms';
$loc = trim($data[2]);
$loc = preg_replace("/(require|include)(_once)?,s*/ix", '', $loc);
$loc = "n" . preg_replace("/,s*/", ",n", $loc) . "n";
dump($query, $duration, $loc);
}
}
if ( $_GET['debug'] == 'cache' )
dump($wp_object_cache->cache);
if ( $_GET['debug'] == 'cron' ) {
$crons = get_option('cron');
foreach ( $crons as $time => $_crons ) {
if ( !is_array($_crons) )
continue;
foreach ( $_crons as $event => $_cron ) {
foreach ( $_cron as $details ) {
$date = date('Y-m-d H:m:i', $time);
$schedule = isset($details['schedule']) ? "({$details['schedule']})" : '';
if ( $details['args'] )
dump("$date: $event $schedule", $details['args']);
else
dump("$date: $event $schedule");
}
}
}
}
return $in;
} # dump_stops()
add_action('init', create_function('$in', '
return add_stop($in, "Load");
'), 10000000);
add_action('template_redirect', create_function('$in', '
return add_stop($in, "Query");
'), -10000000);
add_action('wp_footer', create_function('$in', '
return add_stop($in, "Display");
'), 10000000);
add_action('admin_footer', create_function('$in', '
return add_stop($in, "Display");
'), 10000000);
/**
* init_dump()
*
* @return void
**/
function init_dump() {
global $hook_suffix;
if ( !is_admin() || empty($hook_suffix) ) {
add_action('wp_footer', 'dump_stops', 10000000);
add_action('admin_footer', 'dump_stops', 10000000);
} else {
add_action('wp_footer', 'dump_stops', 10000000);
add_action("admin_footer-$hook_suffix", 'dump_stops', 10000000);
}
} # init_dump()
add_action('wp_print_scripts', 'init_dump');
/**
* dump_phpinfo()
*
* @return void
**/
function dump_phpinfo() {
if ( isset($_GET['debug']) && $_GET['debug'] == 'phpinfo' ) {
phpinfo();
die;
}
} # dump_phpinfo()
add_action('init', 'dump_phpinfo');
/**
* dump_http()
*
* @param array $args
* @param string $url
* @return array $args
**/
function dump_http($args, $url) {
dump(preg_replace("|/[0-9a-f]{32}/?$|", '', $url));
return $args;
} # dump_http()
/**
* dump_trace()
*
* @return void
**/
function dump_trace() {
$backtrace = debug_backtrace();
foreach ( $backtrace as $trace )
dump(
'File/Line: ' . $trace['file'] . ', ' . $trace['line'],
'Function / Class: ' . $trace['function'] . ', ' . $trace['class']
);
} # dump_trace()
if ( $_GET['debug'] == 'http' )
add_filter('http_request_args', 'dump_http', 0, 2);
?>
第七種方案
設置最大數量的修訂版本以避免 DB 膨脹。
測試:Wordpress 3.0.1
默認是無限的,這將設置為只記住最後 5 次編輯:
/**
* Set the post revisions unless the constant was set in wp-config.php
*/
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
FWIW 可以在食典頁面 Editing wp-config.php 上設置一些關於 CONSTANTS 的好主意。
第八種方案
刪除默認 Wordpress 元框
測試:Wordpress 3.0.1
此代碼將允許您刪除默認情況下添加默認的默認添加/編輯帖子和添加/編輯頁面屏幕的特定元框。
// REMOVE META BOXES FROM DEFAULT POSTS SCREEN
function remove_default_post_screen_metaboxes() {
remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
}
add_action('admin_menu','remove_default_post_screen_metaboxes');
// REMOVE META BOXES FROM DEFAULT PAGES SCREEN
function remove_default_page_screen_metaboxes() {
remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
remove_meta_box( 'authordiv','page','normal' ); // Author Metabox
}
add_action('admin_menu','remove_default_page_screen_metaboxes');
第九種方案
將”Wordpress” 移至”WordPress” 過濾器
測試:Wordpress 3.0.1
添加了一個帶有 WordPress 3.0 版本的過濾器,可以將”Wordpress”(無資本 P) 的所有實例自動轉換為”WordPress”(帶有資本 P) 的帖子內容,帖子標題和註釋文本。有人認為這是侵擾性的,我只是需要 mis-case WordPress 的時候,發現過濾器有點惱人。
// Remove annoying P filter
if(function_exists('capital_P_dangit')) {
foreach ( array( 'the_content', 'the_title' ) as $filter )
remove_filter( $filter, 'capital_P_dangit', 11 );
remove_filter('comment_text', 'capital_P_dangit', 31 );
}
第十種方案
鋭化調整大小的圖像 (僅限 jpg)
此功能鋭化調整 jpg 圖像大小。差異的一個例子:
function ajx_sharpen_resized_files( $resized_file ) {
$image = wp_load_image( $resized_file );
if ( !is_resource( $image ) )
return new WP_Error( 'error_loading_image', $image, $file );
$size = @getimagesize( $resized_file );
if ( !$size )
return new WP_Error('invalid_image', __('Could not read image size'), $file);
list($orig_w, $orig_h, $orig_type) = $size;
switch ( $orig_type ) {
case IMAGETYPE_JPEG:
$matrix = array(
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1),
);
$divisor = array_sum(array_map('array_sum', $matrix));
$offset = 0;
imageconvolution($image, $matrix, $divisor, $offset);
imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
break;
case IMAGETYPE_PNG:
return $resized_file;
case IMAGETYPE_GIF:
return $resized_file;
}
return $resized_file;
}
add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
