Wordpress creating shortcode with custom value

2019-09-09 16:56发布

问题:

Hello I have created a simple shortcode to display an image devider.

added this to my functions php:

add_shortcode( 'divider', 'shortcode_insert_divider' );
function shortcode_insert_divider( ) {
return '<div class="divider"></div>';
}

this is the css:

.divider {
  width: 100%;
  height: 55px;
  background-image: url("http....")
}

so this is the shortcode:

 [divider]

Now i'd like to define a different Background image for each time i use the shortcode. How can i implement something like:

[divider src="http://domain.com/image.jpg"]

??? Any Ideas?

回答1:

Here's the code:

function shortcode_insert_divider( $atts ) {

    // Assign default values
    $src_default_value = "";
    $color_default_value = "";

    extract( shortcode_atts( array(
        'src' => $src_default_value,
        'color' => $color_default_value,
    ), $atts ) );

    $html = '<div class="divider" style="color:' . $color . ';background:transparent url(\'' . $src . '\') no-repeat 0 0;"></div>';

    return $html;
}
add_shortcode( 'divider', 'shortcode_insert_divider' );

The "shortcode_atts" allows you get catch these attributes and the "extract" function will allow you go retrieve the data from the array in a easy way.