在 WordPress 中使用短代码的步骤如下:
function my_shortcode_function( $atts ) {
extract( shortcode_atts( array(
'param1' => 'default_value1',
'param2' => 'default_value2',
), $atts ) );
// 将短代码内容放在这里
}
add_shortcode( 'my_shortcode', 'my_shortcode_function' );
在文章或页面中使用短代码,例如 [my_shortcode param1="value1" param2="value2"]
。
保存文章或页面并预览,应该能看到短代码的输出。
注意事项:
add_shortcode
函数注册短代码。extract
函数和 shortcode_atts
函数。[shortcode_name attribute_name="attribute_value"]
的格式来调用该短代码。示例代码:
function my_social_links( $atts ){
$atts = shortcode_atts( array(
'platform' => 'facebook',
'url' => 'https://www.facebook.com/your-account',
), $atts );
$output = '<a href="' . $atts['url'] . '">' .
'<i class="icon-' . $atts['platform'] . '"></i>' .
'</a>';
return $output;
}
add_shortcode( 'social', 'my_social_links' );
在页面中使用 [social platform="twitter" url="https://twitter.com/your-name"]
将输出一个带有 Twitter 图标的链接。