一、WordPress常用功能代码片段
WordPress作为最受欢迎的内容管理系统,通过一些实用代码可以扩展其功能而无需安装额外插件。以下是几个常用的代码片段:
- 禁用自动保存功能:
add_action('admin_init', 'disable_autosave');
function disable_autosave() {
wp_deregister_script('autosave');
}
- 移除WordPress版本号(增强安全性):
remove_action('wp_head', 'wp_generator');
- 限制文章修订版本数量:
define('WP_POST_REVISIONS', 3); // 只保留3个修订版本
二、优化SEO的实用代码
- 自动为图片添加alt属性:
add_filter('the_content', 'auto_image_alt');
function auto_image_alt($content) {
global $post;
preg_match_all('/<img (.*?)\/>/', $content, $images);
if(!is_null($images)) {
foreach($images[1] as $index => $value) {
if(!preg_match('/alt=/', $value)) {
$new_img = str_replace('<img', '<img alt="'.$post->post_title.'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
}
}
}
return $content;
}
- 自动为外部链接添加nofollow属性:
add_filter('the_content', 'auto_nofollow');
function auto_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'auto_nofollow_callback', $content);
}
function auto_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
}
return $link;
}
三、提升网站性能的代码
- 延迟加载图片:
add_filter('the_content', 'lazy_load_content_images');
function lazy_load_content_images($content) {
return preg_replace('/<img([^>]*)src=/i', '<img$1src="data:image/gif;base64,R0lGODdhAQABAPAAAP///wAAACwAAAAAAQABAEACAkQBADs=" data-src=', $content);
}
add_action('wp_footer', 'lazy_load_scripts');
function lazy_load_scripts() {
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
});
</script>
<?php
}
- 禁用Emoji表情(减少HTTP请求):
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
四、增强安全性的代码
- 限制登录尝试次数:
add_filter('authenticate', 'check_attempted_login', 30, 3);
function check_attempted_login($user, $username, $password) {
if (get_transient('attempted_login')) {
$datas = get_transient('attempted_login');
if ($datas['tried'] >= 3) {
$until = get_option('_transient_timeout_'.'attempted_login');
$time = time_to_go($until);
return new WP_Error('too_many_tried', sprintf(__('<strong>错误</strong>: 您已尝试登录太多次,请%s后再试。'), $time));
}
}
return $user;
}
add_action('wp_login_failed', 'login_failed');
function login_failed($username) {
if (get_transient('attempted_login')) {
$datas = get_transient('attempted_login');
$datas['tried']++;
set_transient('attempted_login', $datas, 300);
} else {
$datas = array(
'tried' => 1
);
set_transient('attempted_login', $datas, 300);
}
}
- 禁用XML-RPC接口(防止暴力攻击):
add_filter('xmlrpc_enabled', '__return_false');
五、实用小工具代码
- 显示当前模板路径(开发调试用):
add_action('wp_footer', 'show_template');
function show_template() {
if(is_super_admin()) {
global $template;
echo '<div style="position:fixed;bottom:10px;right:10px;background:#fff;padding:5px;z-index:9999;font-size:12px;">'.basename($template).'</div>';
}
}
- 在文章末尾自动添加版权信息:
add_filter('the_content', 'add_copyright');
function add_copyright($content) {
if(is_single()) {
$content .= '<div class="copyright-notice">本文首发于<a href="'.get_bloginfo('url').'">'.get_bloginfo('name').'</a>,转载请注明出处</div>';
}
return $content;
}
六、代码使用方法
要将这些代码添加到您的WordPress网站,有几种方法:
- 使用子主题的functions.php文件 - 这是最推荐的方法
- 使用代码片段插件 - 如Code Snippets插件
- 创建自定义插件 - 对于更复杂的代码
注意事项:
- 添加代码前务必备份网站
- 一次只添加一个代码片段并测试效果
- 某些代码可能需要根据您的具体需求进行调整
- 定期检查代码兼容性,特别是WordPress更新后
通过合理使用这些WordPress实用代码,您可以显著提升网站的功能性、性能和安全性,同时减少对插件的依赖,使网站运行更加高效稳定。