插件开发文档

短代码(简码)

💡 云策文档标注

概述

Shortcodes 是 WordPress 2.5 引入的宏,用于在内容中实现动态交互,如创建图库或嵌入媒体,同时保持内容语义清洁。

关键要点

  • Shortcodes 允许用户通过简单标记动态修改内容呈现,避免在内容中直接运行 PHP。
  • 内置 Shortcodes 包括 [caption]、[gallery]、[audio]、[video]、[playlist] 和 [embed],用于常见媒体和嵌入功能。
  • 开发 Shortcodes 时需遵循最佳实践:始终返回输出、使用前缀避免冲突、清理输入和转义输出、提供清晰文档。

注意事项

  • Shortcodes 本质上是过滤器,应避免产生副作用,以防止意外错误。

📄 原文内容

As a security precaution, running PHP inside WordPress content is forbidden; to allow dynamic interactions with the content, Shortcodes were presented in WordPress version 2.5.

Shortcodes are macros that can be used to perform dynamic interactions with the content. i.e creating a gallery from images attached to the post or rendering a video.

Why Shortcodes?

Shortcodes are a valuable way of keeping content clean and semantic while allowing end users some ability to programmatically alter the presentation of their content.

When the end user adds a photo gallery to their post using a shortcode, they’re using the least data possible to indicate how the gallery should be presented.

Advantages:

  • No markup is added to the post content, which means that markup and styling can easily be manipulated on the fly or at a later state.
  • Shortcodes can also accept parameters, allowing users to modify how the shortcode behaves on an instance by instance basis.

Built-in Shortcodes

By default, WordPress includes the following shortcodes:

  • – allows you to wrap captions around content
  • – allows you to show image galleries
  • – allows you to embed and play audio files
  • – allows you to embed and play video files
  • – allows you to display collection of audio or video files
  • – allows you to wrap embedded items

Shortcode Best Practices

Best practices for developing shortcodes include the plugin development best practices and the list below:

  • Always return!
    Shortcodes are essentially filters, so creating “side effects” will lead to unexpected bugs.
  • Prefix your shortcode names to avoid collisions with other plugins.
  • Sanitize the input and escape the output.
  • Provide users with clear documentation on all shortcode attributes.

Quick Reference

See the complete example of using a basic shortcode structure, taking care of self-closing and enclosing scenarios, shortcodes within shortcodes and securing output.

External Resources