100 条 functions.php 常用代码片段

1. 启用特色图片支持

add_theme_support( 'post-thumbnails' );

2. 注册导航菜单

function register_my_menu() {
    register_nav_menu('header-menu', __('Header Menu'));
}
add_action('init', 'register_my_menu');

3. 注册小工具区域

function my_widgets_init() {
    register_sidebar( array(
        'name'          => 'Sidebar',
        'id'            => 'sidebar-1',
        'before_widget' => '<section>',
        'after_widget'  => '</section>',
        'before_title'  => '<h2>',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'my_widgets_init' );

4. 添加自定义样式和脚本

function enqueue_my_scripts() {
    wp_enqueue_style('my-style', get_template_directory_uri() . '/css/style.css');
    wp_enqueue_script('my-script', get_template_directory_uri() . '/js/script.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_my_scripts');

5. 禁用 WordPress 的表情符号功能

remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');

6. 修改文章摘要长度

function custom_excerpt_length($length) {
    return 20; // 设置为20个单词
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);

7. 创建自定义短代码

function display_current_year() {
    return date('Y');
}
add_shortcode('current_year', 'display_current_year');

8. 添加自定义登录页面样式

function custom_login_styles() {
    echo '<style>
        body.login {
            background-color: #f0f0f0;
        }
        .login h1 a {
            background-image: url(' . get_template_directory_uri() . '/images/custom-logo.png) !important;
            background-size: contain !important;
        }
    </style>';
}
add_action('login_head', 'custom_login_styles');

9. 禁用 WordPress 的 XML-RPC 功能

add_filter('xmlrpc_enabled', '__return_false');

10. 在登录页面添加自定义消息

function custom_login_message() {
    return '<p class="message">欢迎回来!请登录以继续。</p>';
}
add_filter('login_message', 'custom_login_message');

11. 在登录页面添加自定义链接

function custom_login_url() {
    return home_url();
}
add_filter('login_headerurl', 'custom_login_url');

12. 在登录页面添加自定义标题

function custom_login_title() {
    return get_option('blogname');
}
add_filter('login_headertext', 'custom_login_title');

13. 在登录页面添加自定义徽标

function custom_login_logo() {
    echo '<style>
        .login h1 a {
            background-image: url(' . get_template_directory_uri() . '/images/custom-logo.png) !important;
            background-size: contain !important;
        }
    </style>';
}
add_action('login_head', 'custom_login_logo');

14. 限制用户登录尝试次数

function limit_login_attempts() {
    $max_login_attempts = 5; // 最大尝试次数
    $lockout_duration = 60 * 15; // 锁定时间,单位为秒(这里是15分钟)
    $current_attempts = get_transient('failed_login_attempts');

    if ($current_attempts >= $max_login_attempts) {
        wp_die('您已多次尝试登录,请稍后再试。');
    }
}
add_action('wp_login_failed', 'limit_login_attempts');

15. 在文章页面显示阅读进度条

function reading_progress_bar() {
    if (is_single()) {
        echo '<div id="progress-bar"></div>';
        echo '<script>
            var progress = document.getElementById("progress-bar");
            window.onscroll = function() {
                var scrollPosition = document.documentElement.scrollTop || document.body.scrollTop;
                var docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
                var scrollPercentage = (scrollPosition / docHeight) * 100;
                progress.style.width = scrollPercentage + "%";
            };
        </script>';
    }
}
add_action('wp_footer', 'reading_progress_bar');

16. 自动生成站点地图

function generate_sitemap() {
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    );
    $posts = get_posts($args);

    $sitemap = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach ($posts as $post) {
        $sitemap .= '<url><loc>' . get_permalink($post->ID) . '</loc><lastmod>' . get_the_modified_date('c', $post->ID) . '</lastmod></url>';
    }
    $sitemap .= '</urlset>';

    file_put_contents(ABSPATH . 'sitemap.xml', $sitemap);
}
add_action('publish_post', 'generate_sitemap');

17. 自定义文章类型

function create_custom_post_type() {
    register_post_type('movie', array(
        'labels' => array(
            'name' => 'Movies',
            'singular_name' => 'Movie',
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail'),
    ));
}
add_action('init', 'create_custom_post_type');

18. 允许自定义 HTML 标签在文章中

function allow_custom_html_tags($content) {
    return strip_tags($content, '<p><a><strong><em><img>');
}
add_filter('the_content', 'allow_custom_html_tags');

19. 重定向 WordPress 后台

function redirect_dashboard() {
    if (is_admin()) {
        wp_redirect(home_url());
        exit;
    }
}
add_action('admin_init', 'redirect_dashboard');

20. 禁用 WordPress 评论

function disable_comments() {
    return false;
}
add_filter('comments_open', 'disable_comments', 10, 2);
add_filter('pings_open', 'disable_comments', 10, 2);

21. 设置网站默认语言

function set_default_language() {
    update_option('WPLANG', 'zh_CN');
}
add_action('init', 'set_default_language');

22. 重定向到自定义登录页面

function custom_login_redirect($redirect_to, $request, $user) {
    return home_url();
}
add_filter('login_redirect', 'custom_login_redirect', 10, 3);

23. 隐藏 WordPress 后台 WordPress 版本信息

remove_action('wp_head', 'wp_generator');

24. 禁用后台和前台的 WordPress 更新通知

define('DISALLOW_FILE_MODS', true);

25. 自定义文章的 URL 结构

function custom_permalink_structure() {
    return home_url() . '/%category%/%postname%/';
}
add_filter('pre_option_permalink_structure', 'custom_permalink_structure');

26. 禁用 WordPress 图片自动插入

remove_filter('the_content', 'wp_make_content_images_responsive');

27. 禁用 RSS Feed

remove_action('do_feed', 'do_feed_rss2', 10, 1);

28. 禁用 WordPress 自动保存

define('AUTOSAVE_INTERVAL', 86400); // 单位秒

29. 设置默认头像

function default_avatar($avatar_defaults) {
    $avatar_defaults['my_default_avatar'] = get_template_directory_uri() . '/images/default-avatar.png';
    return $avatar_defaults;
}
add_filter('avatar_defaults', 'default_avatar');

30. 设置页面模板

function my_custom_page_template($page_template) {
    if (is_page('contact')) {
        $page_template = get_template_directory() . '/page-contact.php';
    }
    return $page_template;
}
add_filter('template_include', 'my_custom_page_template');

31. 强制HTTPS协议

function force_ssl() {
    if (!is_ssl()) {
        wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        exit();
    }
}
add_action('template_redirect', 'force_ssl');

32. 为站点页面添加自定义 CSS

function custom_styles() {
    echo '<style>
        body { font-family: Arial, sans-serif; }
    </style>';
}
add_action('wp_head', 'custom_styles');

33. 禁用 WordPress Dashboard Widget

remove_action('wp_dashboard_setup', 'wp_dashboard_widget_function');

34. 通过 AJAX 获取帖子数据

function my_ajax_handler() {
    $args = array(
        'posts_per_page' => 5,
    );
    $posts = get_posts($args);
    foreach ($posts as $post) {
        echo '<h2>' . $post->post_title . '</h2>';
    }
    die();
}
add_action('wp_ajax_my_ajax_request', 'my_ajax_handler');
add_action('wp_ajax_nopriv_my_ajax_request', 'my_ajax_handler');

35. 设置分页链接自定义样式

function custom_pagination($pages = '', $range = 4) {
    $showitems = ($range * 2) + 1;  
    global $paged;
    if (empty($paged)) $paged = 1;
    if ($pages == '') {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if (!$pages) {
            $pages = 1;
        }
    }

    // Generate pagination markup here
}
add_action('wp_footer', 'custom_pagination');

36. 启用短链接功能

add_filter('get_shortlink', 'my_shortlink_function');

37. 显示当前用户名

function current_user_name() {
    echo wp_get_current_user()->display_name;
}
add_shortcode('current_user', 'current_user_name');

38. 禁止某些用户角色进入后台

function restrict_admin_access() {
    if (!current_user_can('administrator') && is_admin()) {
        wp_redirect(home_url());
        exit;
    }
}
add_action('init', 'restrict_admin_access');

39. 将文章自动设置为“草稿”状态

function set_draft_status($post_id) {
    if (get_post_type($post_id) == 'post') {
        wp_update_post(array('ID' => $post_id, 'post_status' => 'draft'));
    }
}
add_action('save_post', 'set_draft_status');

40. 禁用后台所有自定义字段

remove_post_type_support('page', 'custom-fields');

41. 隐藏“编辑”按钮

remove_action('wp_footer', 'wp_edit_button');

42. 自定义后台登录验证错误

function custom_login_error_message() {
    return '用户名或密码错误,请重新尝试。';
}
add_filter('login_errors', 'custom_login_error_message');

43. 为某些页面设置自定义背景

function custom_background_for_page() {
    if (is_page('about')) {
        echo '<style> body { background-color: #f0f0f0; } </style>';
    }
}
add_action('wp_head', 'custom_background_for_page');

44. 定制后台颜色

function custom_admin_color_scheme() {
    echo '<style>
        body { background-color: #333; color: white; }
    </style>';
}
add_action('admin_head', 'custom_admin_color_scheme');

45. 设置自定义帖子标签

function custom_post_tag($post_id) {
    wp_set_post_tags($post_id, 'custom-tag');
}
add_action('publish_post', 'custom_post_tag');

46. 启用自定义登录错误消息

function my_custom_login_error() {
    return '登录失败,请再试一次。';
}
add_filter('login_errors', 'my_custom_login_error');

47. 添加自定义登录表单字段

function custom_login_form_field() {
    echo '<input type="text" name="my_field" placeholder="Enter your info here">';
}
add_action('login_form', 'custom_login_form_field');

48. 清理网站缓存

function clear_cache_on_publish($post_id) {
    if (get_post_type($post_id) == 'post') {
        // 添加清理缓存的逻辑
    }
}
add_action('publish_post', 'clear_cache_on_publish');

49. 更改管理面板菜单顺序

function reorder_dashboard_menu() {
    global $menu;
    $menu[5] = $menu[25]; // 调整菜单项的顺序
}
add_action('admin_menu', 'reorder_dashboard_menu');

50. 设置自动草稿删除周期

define('AUTOSAVE_INTERVAL', 86400);  // 删除周期

51. 为媒体库项添加自定义字段

function add_custom_fields_to_media($form_fields, $post) {
    $form_fields['custom_field'] = array(
        'label' => 'Custom Field',
        'input' => 'text',
        'value' => get_post_meta($post->ID, 'custom_field', true),
    );
    return $form_fields;
}
add_filter('attachment_fields_to_edit', 'add_custom_fields_to_media', 10, 2);

52. 关闭对默认评论的支持

remove_post_type_support('post', 'comments');

53. 显示站点统计信息

function show_site_statistics() {
    echo '文章数:' . wp_count_posts()->publish;
    echo '评论数:' . wp_count_comments()->total_comments;
}
add_shortcode('site_statistics', 'show_site_statistics');

54. 设置自定义的文章封面图

function custom_featured_image($post_id) {
    if (has_post_thumbnail($post_id)) {
        // 设置或更新自定义封面图逻辑
    }
}
add_action('save_post', 'custom_featured_image');

55. 自定义分页样式

function custom_pagination_style($args) {
    // 更改分页样式
    return $args;
}
add_filter('paginate_links', 'custom_pagination_style');

56. 禁止 HTML 的某些标签

function disable_html_tags($content) {
    return strip_tags($content, '<p><a><strong><em>');
}
add_filter('the_content', 'disable_html_tags');

57. 更新文章时记录变更日志

function log_post_changes($post_id) {
    // 记录文章更新日志
}
add_action('save_post', 'log_post_changes');

58. 添加自定义插件检查

function check_plugin_installed() {
    if (!is_plugin_active('plugin-name/plugin-name.php')) {
        // 提示插件未安装
    }
}
add_action('init', 'check_plugin_installed');

59. 创建自定义仪表板小工具

function add_dashboard_widget() {
    wp_add_dashboard_widget('custom_dashboard_widget', 'Custom Widget', 'dashboard_widget_function');
}
function dashboard_widget_function() {
    echo '欢迎使用自定义仪表板小工具!';
}
add_action('wp_dashboard_setup', 'add_dashboard_widget');

60. 显示评论的每个用户的头像

function show_comment_avatars() {
    $comments = get_comments();
    foreach ($comments as $comment) {
        echo get_avatar($comment->user_id);
    }
}
add_action('wp_footer', 'show_comment_avatars');

61. 根据用户角色自定义站点内容

function restrict_content_by_role() {
    if (current_user_can('subscriber')) {
        echo '这是仅供订阅者查看的内容!';
    }
}
add_action('wp_footer', 'restrict_content_by_role');

62. 在文章列表显示发布日期

function custom_post_date($content) {
    if (is_single()) {
        $content .= '<p>' . get_the_date() . '</p>';
    }
    return $content;
}
add_filter('the_content', 'custom_post_date');

63. 将日期格式设置为特定样式

function custom_date_format($date) {
    return date('l, F j, Y', strtotime($date));
}
add_filter('get_the_date', 'custom_date_format');

64. 显示主题的版本号

function theme_version() {
    echo '当前主题版本:' . wp_get_theme()->get('Version');
}
add_action('wp_footer', 'theme_version');

65. 启用简洁页面布局

function enable_minimal_layout() {
    add_filter('body_class', 'minimal_layout_class');
}
function minimal_layout_class($classes) {
    $classes[] = 'minimal-layout';
    return $classes;
}
add_action('wp_footer', 'enable_minimal_layout');

66. 增加外部链接的目标_blank属性

function add_blank_target($content) {
    return preg_replace('/<a(.*?)href=(["\'])((http|https|ftp):\/\/[^\2]*?)\2(.*?)>/i', '<a$1href=$2$3$4target="_blank"$5>', $content);
}
add_filter('the_content', 'add_blank_target');

67. 在页面中禁用右键

function disable_right_click() {
    echo '<script>document.addEventListener("contextmenu", function(e){e.preventDefault();});</script>';
}
add_action('wp_footer', 'disable_right_click');

68. 为文章自动添加“阅读更多”链接

function auto_add_read_more($content) {
    if (is_single()) {
        $content .= '<p><a href="' . get_permalink() . '">继续阅读</a></p>';
    }
    return $content;
}
add_filter('the_content', 'auto_add_read_more');

69. 自定义 WordPress 的加载顺序

function custom_load_order() {
    // 设置文件加载顺序
}
add_action('wp_loaded', 'custom_load_order');

70. 更改后台默认的欢迎消息

function change_welcome_message() {
    return '欢迎回来,管理员!';
}
add_filter('admin_welcome_message', 'change_welcome_message');

71. 通过 AJAX 搜索文章

function ajax_search() {
    if (isset($_POST['search_term'])) {
        $args = array(
            's' => $_POST['search_term'],
            'post_type' => 'post',
        );
        $query = new WP_Query($args);
        while ($query->have_posts()) {
            $query->the_post();
            echo '<h3>' . get_the_title() . '</h3>';
        }
        wp_reset_postdata();
    }
    die();
}
add_action('wp_ajax_search_posts', 'ajax_search');
add_action('wp_ajax_nopriv_search_posts', 'ajax_search');

72. 自定义“添加到购物车”按钮

function custom_add_to_cart_button() {
    echo '<button class="my-add-to-cart">立即购买</button>';
}
add_action('woocommerce_after_shop_loop_item', 'custom_add_to_cart_button');

73. 显示用户评论时的表情

function add_emojis_to_comments($content) {
    return preg_replace('/:smile:/', '😊', $content);
}
add_filter('comment_text', 'add_emojis_to_comments');

74. 强制用户设置个人资料头像

function require_profile_avatar($user_id) {
    if (!get_avatar($user_id)) {
        wp_die('请上传头像!');
    }
}
add_action('user_register', 'require_profile_avatar');

75. 为每篇文章添加相关文章

function display_related_posts() {
    $args = array(
        'posts_per_page' => 5,
        'post__not_in' => array(get_the_ID()),
    );
    $related_posts = new WP_Query($args);
    while ($related_posts->have_posts()) {
        $related_posts->the_post();
        echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    }
}
add_action('wp_footer', 'display_related_posts');

76. 只在特定日期启用某些功能

function enable_feature_on_special_date() {
    if (date('Y-m-d') == '2025-12-25') {
        // 启用特定功能
    }
}
add_action('wp_loaded', 'enable_feature_on_special_date');

77. 通过主题选项添加自定义代码

function custom_theme_options() {
    // 在主题选项中增加代码
}
add_action('admin_menu', 'custom_theme_options');

78. 设置每个分类的封面图

function custom_category_image($category_id) {
    if (has_term('some-category', 'category')) {
        // 设置该分类的封面图
    }
}
add_action('category_header', 'custom_category_image');

79. 自定义页面的侧边栏

function custom_sidebar_content() {
    echo '<p>自定义侧边栏内容</p>';
}
add_action('get_sidebar', 'custom_sidebar_content');

80. 更改 WordPress 默认登录重定向

function custom_login_redirect($redirect_to, $request, $user) {
    if (isset($user->roles) && in_array('administrator', $user->roles)) {
        return admin_url();
    } else {
        return home_url();
    }
}
add_filter('login_redirect', 'custom_login_redirect', 10, 3);

81. 启用异步加载的 JS 文件

function async_load_js() {
    echo '<script async src="' . get_template_directory_uri() . '/js/async.js"></script>';
}
add_action('wp_footer', 'async_load_js');

82. 自定义用户注册时发送邮件

function custom_registration_email($user_id) {
    $user = get_user_by('id', $user_id);
    wp_mail($user->user_email, '欢迎注册', '感谢您注册我们的网站!');
}
add_action('user_register', 'custom_registration_email');

83. 自定义用户登录后邮件通知

function custom_login_email($user_login, $user) {
    wp_mail($user->user_email, '登录成功', '欢迎回来,' . $user->display_name);
}
add_action('wp_login', 'custom_login_email', 10, 2);

84. 更改 WordPress 默认上传的图片尺寸

function custom_image_sizes() {
    set_post_thumbnail_size(600, 400); // 设置自定义图片尺寸
}
add_action('after_setup_theme', 'custom_image_sizes');

85. 自动更新插件

add_filter('auto_update_plugin', '__return_true');

86. 显示短链接

function show_short_link() {
    echo get_shortlink();
}
add_shortcode('short_link', 'show_short_link');

87. 禁用 WordPress 图像缩放

remove_filter('the_content', 'wp_make_content_images_responsive');

88. 为页面设置默认模板

function set_default_page_template($template) {
    return get_template_directory() . '/page-default.php';
}
add_filter('page_template', 'set_default_page_template');

89. 添加自定义的后台菜单

function add_custom_admin_menu() {
    add_menu_page('Custom Admin', '自定义后台', 'manage_options', 'custom-admin', 'custom_admin_page');
}
function custom_admin_page() {
    echo '自定义后台内容';
}
add_action('admin_menu', 'add_custom_admin_menu');

90. 修改 WordPress 默认的文章排序

function modify_post_order($query) {
    if ($query->is_main_query() && !is_admin()) {
        $query->set('orderby', 'title');
        $query->set('order', 'ASC');
    }
}
add_action('pre_get_posts', 'modify_post_order');

91. 禁用后台文章编辑器

remove_post_type_support('post', 'editor');

92. 禁用 WordPress 的“激活”页面

add_filter('wp_site_admin_url', 'custom_admin_url');

93. 禁用后台的 WordPress 版本更新

remove_action('admin_init', '_maybe_update_core');

94. 为新用户自动添加角色

function assign_role_to_new_user($user_id) {
    $user = new WP_User($user_id);
    $user->add_role('editor');  // 为新用户自动添加角色
}
add_action('user_register', 'assign_role_to_new_user');

95. 强制使用 HTTPS

function force_ssl_login() {
    if (!is_ssl() && $_SERVER['REQUEST_URI'] != '/wp-login.php') {
        wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        exit;
    }
}
add_action('template_redirect', 'force_ssl_login');

96. 显示访问网站的设备类型

function show_device_type() {
    if (wp_is_mobile()) {
        echo '您正在使用移动设备访问本站。';
    } else {
        echo '您正在使用桌面设备访问本站。';
    }
}
add_action('wp_footer', 'show_device_type');

97. 禁用 WooCommerce 评论功能

function disable_woocommerce_comments() {
    remove_post_type_support('product', 'comments');
}
add_action('init', 'disable_woocommerce_comments');

98. 修改“返回首页”的链接

function custom_home_link($url) {
    return home_url('/custom-home/');
}
add_filter('home_url', 'custom_home_link');

99. 自定义注册表单

function custom_registration_form() {
    echo '<input type="text" name="custom_field" placeholder="输入自定义字段">';
}
add_action('register_form', 'custom_registration_form');

100. 禁用后台登录尝试

function block_login_attempts() {
    if ($_SERVER['REQUEST_URI'] === '/wp-login.php') {
        wp_die('禁止后台登录');
    }
}
add_action('init', 'block_login_attempts');
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇