欢迎光临
我们一直在努力

WordPress函数文件常用自定义代码

functions.php文件是WordPress主题里面的主要功能文件,通过这个文件,可以实现很多类似插件的功能,所以很多插件功能都是可以通过functions.php这个文件搞定的,今天云落就将自己收集的一些代码整理下,如果有用的话,希望点个赞吧。
前言

在这篇文章中,云落提供了自定义函数来增强你的WordPress网站。这些代码将帮助您优化你的WordPress网站,同时加强 WordPress的功能。但是并非一切代码都是可以使用的,截取其中你主机需要的,并添加自己的自定义functions.php文件,以下代码都是可 以直接加入functions.php文件的。

版权声明

本文欢迎转载,但是必须保留本文链接,谢谢合作!

在header中添加RSS链接

// add feed links to header
if (function_exists('automatic_feed_links')) {
automatic_feed_links();
} else {
return;
}

加载自定义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');
}

适应层叠评论

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

去除多余头部信息代码

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

在footer添加统计代码

其实比较鸡肋的,因为很多主题都自带的

// add tongji to footer
function add_tongji() {
echo '<script src="统计代码" type="text/javascript"></script>';
}
add_action('wp_footer', 'add_tongji');

自定义摘要长度

// custom excerpt length
function custom_excerpt_length($length) {
return 80;
}
add_filter('excerpt_length', 'custom_excerpt_length');

自定义摘要结尾的截断

// custom excerpt ellipses for 2.9+
function custom_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');

自定义摘要结尾的继续阅读

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

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

添加代码之后,在WordPress根目录扔一个favicon.ico图标文件。

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

在主题img里面扔一个favicon.ico图标文件,这里的图标只有在网站后台看到的

自定义登陆页面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');

在主题img目录扔一个登陆logo图片

禁用小工具

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

取消后台的更新提示

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

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

获取第一个分类id

// get the first category id
function get_first_category_ID() {
$category = get_the_category();
return $category[0]->cat_ID;
}

使用的时候使用<?php get_first_category_ID(); ?>标签获取数值。

在面额文章以及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');

隐藏WordPress版本号

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

自定义后台左下角的文字

// customize admin footer text
function custom_admin_footer() {
echo '么么哒';
}
add_filter('admin_footer_text', 'custom_admin_footer');

用户描述里面使用HTML代码

// enable html markup in user profiles
remove_filter('pre_user_description', 'wp_filter_kses');

文章发布之后延迟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');

后台菜单添加所有设置菜单

首先说下设置页面,就是这个页面:http://你的域名/wp-admin/options.php 进去之后是你的网站的全部数据表单,某些设置可能需要在这里设置
[v_error]危险区域,一般别改东西[/v_error]

// admin link for all settings
function all_settings_link() {
add_options_page(__('全部设置'), __('全部设置'), 'administrator', 'options.php');
}
add_action('admin_menu', 'all_settings_link');

移除评论中的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');

给评论添加垃圾,删除按钮

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

使用<?php delete_comment_link(get_comment_ID()); ?>标签显示按钮

彻底禁用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);

自定义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');

转换评论中的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');

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

去除文章图片自动添加尺寸的问题

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

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

使用短代码使用bloginfo函数

function digwp_bloginfo_shortcode( $atts ) {
extract(shortcode_atts(array(
'key' => '',
), $atts));
return get_bloginfo($key);
}
add_shortcode('bloginfo', 'digwp_bloginfo_shortcode');

使用的时候,这样就好了[bloginfo key=’name’]

使用短代码防止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]

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

在控制面板创建一个小工具

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

控制面板创建一个表格小工具

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

}

}

更换控制面板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>
';
}

禁用可视化编辑器自动补全标签

//disable wpautop filter
remove_filter ('the_content', 'wpautop');

增加减少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' );

添加图片附件上传时候的默认项

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

图片上传时候添加自定义尺寸

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

更换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');

主题激活后自动创建页面

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

}

非管理员不得访问后台

add_action( 'init', 'blockusers_wps_init' );
function blockusers_wps_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) ) {
wp_redirect( home_url() );//滚回首页吧
exit;
}
}

用户注册成功后跳转

function wps_registration_redirect(){
return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );

给自定义文章添加概览计数

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

给可视化编辑器添加短代码

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

给文章添加特色图才给发布,否则不给发

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

}

要求评论字数的最小值

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

用颜色区分后台文章的状态

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
}

给特定文章/页面强制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);

给后台添加指引

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
}

给WordPress添加欢迎信息

<?php if( strpos($_SERVER[HTTP_REFERER], "baidu.com" ) == true ): ?>
<div class="welcome-stumbleupon">
<p>欢迎来自百度的亲们!</p>
</div>
<?php endif; ?>
注意:本段代码是添加在主题header.php文件里面的,自己辅助下样式吧

角色变换时候发送电子邮件

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

短代码添加一个网站的截图

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://googlo.me&#8221; alt=”wordpress code snippets for your blog” width=”200″ height=”200″]

使用短代码添加倒计时功能

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]

强制控制面板显示一列

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

让登陆用户自己选择登陆后的跳转

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

原文链接:http://googlo.me/archives/3693.html

窗外天空
关注公众号『窗外天空』

获取更多建站运营运维新知!
互联网创业、前沿技术......

赞(0) 打赏
文章名称:《WordPress函数文件常用自定义代码》
文章链接:https://www.nixonli.com/18351.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

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

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏