你需要拥有WordPress站点的主题文件编辑权限,两种获取方式二选一:
操作前必须先备份functions.php文件,如果编辑后网站出现500错误,直接用备份文件覆盖即可恢复,无需额外排查。
无参数短代码适合做固定功能的调用,比如站点底部版权栏的动态年份,无需每年手动修改更新。
将以下代码完整粘贴到functions.php文件的最底部,保存即可:
```php // 注册动态年份短代码 [current_year] function custom_current_year_shortcode() { return date('Y'); } add_shortcode('current_year', 'custom_current_year_shortcode'); ```在文章、页面、文本小工具中直接输入[current_year],前台就会自动显示当前的公历年,比如2024。
带参数的短代码支持调用时自定义属性,适合制作可灵活配置的元素,比如自定义跳转按钮。

将以下代码粘贴到functions.php最底部:
```php // 注册自定义按钮短代码 调用格式:[custom_btn text="按钮文字" link="跳转地址" bg_color="背景色"] function custom_btn_shortcode($atts) { // 提取参数并设置默认值,未传参时自动使用默认值 $atts = shortcode_atts( array( 'text' => '点击查看', 'link' => '', 'color' => 'ffffff', 'bg_color' => '2563eb', 'target' => '_blank' ), $atts ); // 拼接按钮HTML代码,所有输出添加转义保证安全 return ''.esc_html($atts['text']).''; } add_shortcode('custom_btn', 'custom_btn_shortcode'); ```输入短代码时按需传入参数即可,示例:
[custom_btn text="跳转到百度" link="https://www.baidu.com" bg_color="f43f5e"]
上述代码会生成一个粉色背景、文字为“跳转到百度”的按钮,点击后新窗口打开百度。如果不传参数,会自动使用默认配置生成蓝色默认按钮。
注意事项:如果参数值包含空格、特殊符号,必须用英文双引号包裹,否则参数会解析失败。
闭合型短代码支持包裹自定义内容,适合制作内容高亮框、通知栏这类需要传入内容的模块。
将以下代码粘贴到functions.php最底部:
```php // 注册内容高亮短代码 调用格式:[highlight type="warning"]要高亮的内容[/highlight] function custom_highlight_shortcode($atts, $content = null) { // 提取参数并设置默认值 $atts = shortcode_atts( array( 'type' => 'info' // 支持4种类型:info/warning/success/error ), $atts ); // 对应类型的预设样式 $style_config = [ 'info' => 'background:eff6ff;border-left:4px solid 2563eb;padding:12px 16px;border-radius:0 4px 4px 0;margin:12px 0;line-height:1.6;', 'warning' => 'background:fffbeb;border-left:4px solid f59e0b;padding:12px 16px;border-radius:0 4px 4px 0;margin:12px 0;line-height:1.6;', 'success' => 'background:f0fdf4;border-left:4px solid 10b981;padding:12px 16px;border-radius:0 4px 4px 0;margin:12px 0;line-height:1.6;', 'error' => 'background:fef2f2;border-left:4px solid ef4444;padding:12px 16px;border-radius:0 4px 4px 0;margin:12px 0;line-height:1.6;' ]; // do_shortcode支持短代码嵌套,即包裹的内容中也可以使用其他短代码 return '用短代码包裹需要高亮的内容即可,示例:
[highlight type="success"]本文所有代码均经过实测,可直接复制使用[/highlight]
上述代码会生成一个绿色边框的成功提示框,显示对应的内容。
add_filter('the_meta_key', 'do_shortcode');
include 'custom-shortcode.php';即可,方便后续维护。易频IT社区是综合性互联网IT技术门户网站,专注分享网络技术、服务器运维、网络安全、编程开发、系统架构、云计算、大数据等行业干货,实时更新IT行业资讯、零基础教程、实战案例,为IT从业者、技术爱好者提供专业的学习交流平台。
Copyright © 2021-2026 易频IT社区. All Rights Reserved. 备案号:闽ICP备2023013482号 网站地图