Detecting parameter names in php function for wordpress shortcode?

廉价感情. 提交于 2019-12-24 12:01:32

问题


I am trying yo understand this function, as a preface to forking it to make similar functions for my own shortcodes. I understand how to define shortcodes and their functions. I also basically "get" what the original author is doing here: collecting parameters from the shortcode and assembling them into an HTML tag and returning that tag. It seems the order of the params is unimportant, but their names are.

However, when I am working with this code, it does not seem to understand which param is which. For example, the original docs say to use the shortcode like so: [button link="http://google.com" color="black" size="small"]Button Text[/button]

But when I use this shortcode, I get:

<a href="Button Text" title="Array" class="button button-small button " target="_self">
  <span>Array</span>
</a>

Here's my PHP:

if( ! function_exists( 'make_button' ) ) {
function make_button( $text, $url, $color = 'default', $target = '_self', $size = 'small', $classes = null, $title = null ) {
    if( $target == 'lightbox' ) {
        $lightbox = ' rel="lightbox"';
        $target = null;
    } else {
        $lightbox = null;
        $target = ' target="'.$target.'"';
    }
    if( ! $title )
        $title = $text;
    $output = '<a href="'.$url.'" title="'.$title.'" class="button button-'.$size.' '.$color.' '.$classes.'"'.$target.$lightbox.'>';
    $output .= '<span>'.$text.'</span>';
    $output .= '</a>';
    return $output;
}
}


add_shortcode( 'button', 'make_button' );

回答1:


See the documentation for Shortcode API, there clearly states that three parameters are passed to the shortcode callback function:

  • $atts - an associative array of attributes, or an empty string if no attributes are given
  • $content - the enclosed content (if the shortcode is used in its enclosing form)
  • $tag - the shortcode tag, useful for shared callback functions

So the function definition should look like:

function make_button( $atts, $content, $tag ) {
    // use print_r to examine attributes
    print_r($atts);
}



回答2:


The shortcode is explicitly looking for $text.

[button url="http://google.com" color="black" size="small" text="Button Text"]

Typically the variable that is set when you use the open/close shortcode is $content, per the Shortcode API. Another fix would be to change the shortcode to look for $content instead of $text.



来源:https://stackoverflow.com/questions/18315826/detecting-parameter-names-in-php-function-for-wordpress-shortcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!