在WordPress新建文章中添加默认代码的实现疑问
嘿,我来帮你搞定在WordPress新建文章时默认添加指定内容的需求~
方法1:用default_content钩子添加Shortcodes Ultimate短代码
你之前的思路完全没问题,只需要把想要的短代码直接整合到my_editor_content函数里就行,WordPress会自动解析已激活插件的短代码。把这段代码放到你的主题(或子主题)的functions.php文件中:
add_filter( 'default_content', 'my_editor_content' ); function my_editor_content( $content ) { // 先添加你想要的提示文字 $content = "If you like this post, then please consider retweeting it or sharing it on Facebook.\n\n"; // 再拼接Shortcodes Ultimate的折叠框短代码 $content .= '[su_spoiler title="Download The File" style="fancy" icon="chevron-circle"]Here[/su_spoiler]'; return $content; }
👉 注意:要确保Shortcodes Ultimate插件处于激活状态,不然短代码会以纯文本形式显示。
方法2:用原生HTML代替短代码(无需插件)
如果你不想依赖第三方插件,也可以用原生HTML的details/summary标签实现折叠效果,代码如下:
add_filter( 'default_content', 'my_editor_content' ); function my_editor_content( $content ) { $content = "If you like this post, then please consider retweeting it or sharing it on Facebook.\n\n"; $content .= '<details style="border: 1px solid #eee; border-radius: 4px; padding: 0.5rem;"> <summary style="cursor: pointer; font-weight: 600; margin-bottom: 0.5rem;">Download The File</summary> <p>Here</p> </details>'; return $content; }
这种方式的好处是不用依赖插件,兼容性也很好,大部分现代浏览器都支持。
小提醒
- 修改
functions.php前记得备份文件,或者优先使用子主题的functions.php,避免主题更新后代码被覆盖。 - 不管是用短代码还是HTML,在古腾堡编辑器里会自动识别对应的内容块,经典编辑器则直接显示解析后的效果。
内容的提问来源于stack exchange,提问作者Dhrubajyoti Dutta
相关产品推荐
相关产品推荐

