服务器与VPS
促销优惠信息

自己建站用户常用的WordPress模板functions.php函数

使用wordpress建站的用户越来越多,除了wordpress主题模板中自带的功能,有一些个性化需求可以通过安装wordpress插件来实现,但是有的用户不想装太多插件,那就可以通过在主题的functions.php”文件中添加代码来实现。纯代码也可以做到插件实现的功能,以下是一些常用的function函数:

比如很多朋友在找的复制文章添加版权弹窗功能:

//复制提示保留版权 2023-12-19
function zm_copyright_tips() {
echo '<link rel="stylesheet" type="text/css" rel="external nofollow" target="_blank" href="https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.css" >';
echo '<script src="https://cdn.bootcss.com/sweetalert/1.1.3/sweetalert.min.js"></script>';
echo '<script>document.body.oncopy = function() { swal("复制成功!", "转载请务必保留原文链接,申明来源,谢谢合作!!","success");};</script>';
}
add_action( 'wp_footer', 'zm_copyright_tips', 100 );

以下是更多自己建站常用的”functions.php”函数,可以实现很多个性化功能:

1、在header中添加RSS链接

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

2、去除多余头部信息代码

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

3、自定义摘要长度

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

4、自定义摘要结尾的截断

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

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

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

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

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

注:这里的网站图标只有在后台才能看到,前台不受影响,前后后两种图标。
8、自定义登陆页面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”即可。
9、禁用小工具

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

10、取消wordpress后台的更新提示

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

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

12、获取第一个分类id

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

13、隐藏WordPress版本号

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

14、自定义后台左下角的文字

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

15、用户描述里面使用HTML代码

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

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

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

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

这个页面是wordpress的全部数据表单,危险区域慎动!

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

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

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

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

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

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

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

24、短代码使用bloginfo函数

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

25、使用短代码防止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]
26、通过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;
}

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

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

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

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

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

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

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

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

32、主题激活后自动创建页面

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

33、禁止非管理员用户访问后台

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

34、用户注册成功后跳转

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

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

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

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

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

37、要求文章添加特色图才能发布,否则不给发

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

38、要求评论字数的最小值

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

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

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
}

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

41、给后台添加指引

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>XX网站的通知</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
}

42、给WordPress添加欢迎信息

<?php if( strpos($_SERVER[HTTP_REFERER], "baidu.com" ) == true ): ?> <div class="welcome-stumbleupon"> <p>欢迎来自百度的亲们!</p> </div>
<?php endif; ?>

注:此段是加在主题目录下“header.php”文件中,样式自己另行增加。
43、角色变换时候发送电子邮件

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

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

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="'%20.%20$screenshot%20.%20''%20.%20urlencode($url)%20.%20'?w='%20.%20$width%20.%20'&h='%20.%20$height%20.%20'" alt="' . $alt . '"/>';
}
add_shortcode("screenshot", "wps_screenshot");

用法:
[screenshot url=”https://www.chukuangren.com” alt=”wordpress code snippets for your blog” width=”200″ height=”200″]
45、使用短代码添加倒计时功能

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=”2023″]本次活动已过期,请下次再来!-楚狂人[/cdt]
46、强制控制面板显示一列

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

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

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

以上是网络搜集的wordpress建站常用的自定义功能代码,这些functions.php函数可以帮助我们实现与众不同的网站功能。

楚狂人 » 自己建站用户常用的WordPress模板functions.php函数

相关推荐

  • 暂无文章

评论 抢沙发

  • (必填)
  • (必填)

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

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

支付宝扫一扫打赏

微信扫一扫打赏