按钮短代码

这是一个简单按钮短代码的示例:

<?php
function my_button_shortcode( $atts ) {

    // Parse the input attributes and assgn default values for the 
    // attributes that are not specified on the shortcode
    $a = shortcode_atts( array(
        'id' => '',
        'url' => '#',
        'class' => '',
        'text' => ''
    ), $atts );

    // Open the anchor tag and add role=button for better accessibility
    $btn_html = '<a role="button"';

    // Add the href(link) attribute
    $btn_html .= ' href="' . $a['url'] . '"';

    // Add id attribute to output if specified
    if ( !empty( $a['id'] ) ) {
        $btn_html .= ' id="' . $a['id'] . '"';
    }

    $btn_classes = 'button';

    // Add class attribute to output
    $btn_html .= ' class="button ' . ( !empty(a['class']) ? $a['class'] : '' ) . '"';

    // Close opening anchor tag
    $btn_html .= '>'.
        // Add button text
        $a['text'].
        // Add closing anchor tag
        '</a>'."\n";

    return $btn_html;
}
add_shortcode( 'button', 'my_button_shortcode' );

可以通过在编辑器中键入 [button url="/my-other-page" id="my-other-page-button" class="dark" text="Click me!"] 来使用此短代码,并输出以下 HTML:

<a role="button" href="/my-other-page" id="my-other-page-button" 
class="button dark">Click me!</a>