ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
现在我们知道如何创建一个基本的短代码,以及如何使用它作为自我关闭和封闭,我们将使用短代码`[$tag]`和处理函数中的参数。 短码`[$tag]`可以接受参数,称为属性: ``` [wporg title="WordPress.org"] Having fun with WordPress.org shortcodes. [/wporg] ``` Shortcode处理函数可以接受3个参数: $atts - array - [$tag]属性 $content - string - 发布内容 $tag - string - [$tag]的名称(即短码的名称) ``` function wporg_shortcode($atts = [], $content = null, $tag = '') {} ``` ## 解析属性 对于用户来说,短信只是在帖子内容中带有方括号的字符串。 用户不知道哪些属性可用,幕后发生什么。 对于插件开发人员,无法强制使用属性的策略。 用户可以包括一个属性,两个或全部。 为了控制如何使用短码: - 声明处理函数的默认参数 - 使用array_change_key_case()对属性数组执行关键案例的归一化 - 使用shortcode_atts()提供默认值array和user $ atts来解析属性 - 在返回之前确保输出 ## 完整例子 完整的示例使用基本的短代码结构,处理自我关闭和封闭场景,缩短代码并确保输出。 一个[wporg]短码,将接受一个标题,并将显示一个框,我们可以用CSS风格。 ``` <?php function wporg_shortcode($atts = [], $content = null, $tag = '') { // normalize attribute keys, lowercase $atts = array_change_key_case((array)$atts, CASE_LOWER); // override default attributes with user attributes $wporg_atts = shortcode_atts([ 'title' => 'WordPress.org', ], $atts, $tag); // start output $o = ''; // start box $o .= '<div class="wporg-box">'; // title $o .= '<h2>' . esc_html__($wporg_atts['title'], 'wporg') . '</h2>'; // enclosing tags if (!is_null($content)) { // secure output by executing the_content filter hook on $content $o .= apply_filters('the_content', $content); // run shortcode parser recursively $o .= do_shortcode($content); } // end box $o .= '</div>'; // return output return $o; } function wporg_shortcodes_init() { add_shortcode('wporg', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ```