首页 问答 正文

如何在wordpress中启用和使用简码(shortcode)?

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

在WordPress中,简码(shortcode)是一种简单的方式,用于向文章或页面添加动态功能或内容。 简码是由方括号([])包围的文本,它会在发布后自动转换为预定义的HTML或其他代码。

要在WordPress中创建简码,请使用add_shortcode函数。以下示例向您展示如何为简码添加功能:

function my_custom_shortcode( $atts ) {
   // Add your shortcode functionality here
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' ); 

在此示例中,'my_shortcode'是您的简码名称,'my_custom_shortcode'是处理简码功能的函数名称。

有些简码需要参数。在这种情况下,您可以在$atts数组中传递参数。例如,以下示例向您展示如何使用参数创建简码:

function my_custom_shortcode( $atts ) {
   $atts = shortcode_atts( array(
      'param1' => 'default value',
      'param2' => 'default value',
   ), $atts );

   // Add your shortcode functionality here
   $output = 'Param 1: ' . $atts['param1'] . '<br>';
   $output .= 'Param 2: ' . $atts['param2'];

   return $output;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' ); 

在此示例中,shortcode_atts函数将从传递的参数数组中获取所有参数,并将它们与默认值合并。然后,您可以使用这些值来执行您的简码功能,并返回您想要的内容或输出。

在文章或页面中使用简码时,请在方括号中使用您的简码名称,并为参数添加任何必要的值。例如:

[my_shortcode param1="value1" param2="value2"] 

当您发布文章或页面时,WordPress将自动将简码转换为您定义的HTML或其他代码,并向站点访问者显示结果。

大家谈论
    我的见解