Wordpress creating shortcode with custom value

你离开我真会死。 提交于 2019-12-12 01:24:50

问题


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.



来源:https://stackoverflow.com/questions/23784363/wordpress-creating-shortcode-with-custom-value

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