首页 问答 正文

如何在wordpress中使用短代码?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 157 次

在 WordPress 中使用短代码的步骤如下:

  1. 编写短代码函数,可以在主题的 functions.php 文件中编写,示例代码如下:
function my_shortcode_function( $atts ) {
    extract( shortcode_atts( array(
        'param1' => 'default_value1',
        'param2' => 'default_value2',
    ), $atts ) );

    // 将短代码内容放在这里

}
add_shortcode( 'my_shortcode', 'my_shortcode_function' ); 
  1. 在文章或页面中使用短代码,例如 [my_shortcode param1="value1" param2="value2"]

  2. 保存文章或页面并预览,应该能看到短代码的输出。

注意事项:

  • 使用 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 图标的链接。

大家谈论
    我的见解