超实用的WordPress函数文件functions代码收集整理

与许多人现在看这篇文章,我一直在阅读各种博客、论坛、讨论组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');

除了管理用户删除所有用户更新通知

测试: WordPress 3.0.1

这段代码将确保没有用户除了“admin”由wordpress更新可用时通知. .

// 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;" ) );
}

修改登录图片与链接

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;
}

加载自定义jquery库

这里是调用谷歌jquery库

// 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://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
wp_enqueue_script( 'jquery' );
}
}

移除WordPress版本号

// remove version info from head and feeds
function complete_version_removal() {
return '';
}
add_filter('the_generator', 'complete_version_removal');

添加垃圾评论删除链接

// 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订阅显示内容

// 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');

限制数据库文章版本数

代码添加到wp-config.php

/**
* Set the post revisions unless the constant was set in wp-config.php
*/
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);

在搜索结果中包括自定义文章类型

// 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提要。

// 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' );

包括自定义职位类型在“现在”管理仪表板小部件

这将包括您的自定义职位类型和每种类型的帖子数量的“现在”仪表板小部件。

// 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' );

删除默认Wordpress mate box

// 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');

或者更简单的

function remove_post_meta_box() {
remove_meta_box('slugdiv', 'post', 'normal');
}
add_action('admin_menu', 'remove_post_meta_box');

删除“Wordpress”“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 );
}

定制管理菜单的顺序

这段代码将允许您重组元素的顺序在管理菜单。 所有你需要做的就是在管理菜单,点击现有链接复制之前的一切/ wp-admin / URL。 下面的订单代表了新管理菜单的顺序。

// CUSTOMIZE ADMIN MENU ORDER
function custom_menu_order($menu_ord) {
if (!$menu_ord) return true;
return array(
'index.php', // this represents the dashboard link
'edit.php?post_type=events', // this is a custom post type menu
'edit.php?post_type=news',
'edit.php?post_type=articles',
'edit.php?post_type=faqs',
'edit.php?post_type=mentors',
'edit.php?post_type=testimonials',
'edit.php?post_type=services',
'edit.php?post_type=page', // this is the default page menu
'edit.php', // this is the default POST admin menu
);
}
add_filter('custom_menu_order', 'custom_menu_order');
add_filter('menu_order', 'custom_menu_order');

自定义仪表盘

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
global $wp_meta_boxes;

删除这些仪表盘……

unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

添加一个名为“帮助和支持”的自定义小部件

wp_add_dashboard_widget('custom_help_widget', 'Help and Support', 'custom_dashboard_help');
}

这是您的自定义小部件的内容

function custom_dashboard_help() {
echo '<p>Lorum ipsum delor sit amet et nunc</p>';
}

函数改变文章摘要的长度

function new_excerpt_length($length) {
return 100;
}

add_filter('excerpt_length', 'new_excerpt_length');

自动从文章内容中提取第一个图像

这段代码将自动提取第一个图像与一个帖子和允许您显示/通过调用getImage函数中使用它。

// AUTOMATICALLY EXTRACT THE FIRST IMAGE FROM THE POST
function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
$start=$imgEnd+1;
}
if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
$more = 0;
}

删除ping到您自己的博客

//remove pings to self
function no_self_ping( &$links ) {
$home = get_option( 'home' );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
unset($links[$l]);
}
add_action( 'pre_ping', 'no_self_ping' );

自动压缩图片大小(只有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);

启用GZIP压缩输出

通常情况下,服务器应该设置为自动,但大量的共享主机 不这样做(可能增加客户端带宽使用情况)

if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));

显示数据库查询,时间和内存消耗

代码插入公共网站的页脚(确保你的主题是调用wp_footer):

function performance( $visible = false ) {

$stat = sprintf( '%d queries in %.3f seconds, using %.2fMB memory',
get_num_queries(),
timer_stop( 0, 3 ),
memory_get_peak_usage() / 1024 / 1024
);

echo $visible ? $stat : "<!-- {$stat} -->" ;
}
add_action( 'wp_footer', 'performance', 20 );

只有不活跃的插件删除插件更新通知

function update_active_plugins($value = '') {
/*
The $value array passed in contains the list of plugins with time
marks when the last time the groups was checked for version match
The $value->reponse node contains an array of the items that are
out of date. This response node is use by the 'Plugins' menu
for example to indicate there are updates. Also on the actual
plugins listing to provide the yellow box below a given plugin
to indicate action is needed by the user.
*/
if ((isset($value->response)) && (count($value->response))) {

// Get the list cut current active plugins
$active_plugins = get_option('active_plugins');
if ($active_plugins) {

// Here we start to compare the $value->response
// items checking each against the active plugins list.
foreach($value->response as $plugin_idx => $plugin_item) {

// If the response item is not an active plugin then remove it.
// This will prevent WordPress from indicating the plugin needs update actions.
if (!in_array($plugin_idx, $active_plugins))
unset($value->response[$plugin_idx]);
}
}
else {
// If no active plugins then ignore the inactive out of date ones.
foreach($value->response as $plugin_idx => $plugin_item) {
unset($value->response);
}
}
}
return $value;
}
add_filter('transient_update_plugins', 'update_active_plugins'); // Hook for 2.8.+
//add_filter( 'option_update_plugins', 'update_active_plugins'); // Hook for 2.7.x

注销WP默认窗口小部件

// unregister all default WP Widgets
function unregister_default_wp_widgets() {
unregister_widget('WP_Widget_Pages');
unregister_widget('WP_Widget_Calendar');
unregister_widget('WP_Widget_Archives');
unregister_widget('WP_Widget_Links');
unregister_widget('WP_Widget_Meta');
unregister_widget('WP_Widget_Search');
unregister_widget('WP_Widget_Text');
unregister_widget('WP_Widget_Categories');
unregister_widget('WP_Widget_Recent_Posts');
unregister_widget('WP_Widget_Recent_Comments');
unregister_widget('WP_Widget_RSS');
unregister_widget('WP_Widget_Tag_Cloud');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);

输出该主题模板文件头一篇文章/页使用

add_action('wp_head', 'show_template');
function show_template() {
global $template;
print_r($template);
}

删除不需要的仪表板项目

add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');

function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
//Right Now - Comments, Posts, Pages at a glance
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
//Recent Comments
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
//Incoming Links
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
//Plugins - Popular, New and Recently updated WordPress Plugins
unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);

//Wordpress Development Blog Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
//Other WordPress News Feed
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
//Quick Press Form
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
//Recent Drafts List
unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
}

未经允许不得转载:窗外天空 » 超实用的WordPress函数文件functions代码收集整理

赞 (0)

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址