最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

shortcode - What does extract( shortcode_atts( array( do?

programmeradmin1浏览0评论

The codex says

shortcode_atts() combines user shortcode attributes with known attributes and fills in defaults when needed. The result will contain every key from the known attributes, merged with values from shortcode attributes.

It doesn't make much sense to me (I'm a newbie).

Here is an example:

function wps_trend($atts) {
    extract( shortcode_atts( array(
        'w' => '500', 
        'h' => '330',
        'q' => '',
        'geo' => 'US',
    ), $atts));
    $h = (int) $h;
    $w = (int) $w;
    $q = esc_attr($geo);
    ob_start();  

Please can you explain?

The codex says

shortcode_atts() combines user shortcode attributes with known attributes and fills in defaults when needed. The result will contain every key from the known attributes, merged with values from shortcode attributes.

It doesn't make much sense to me (I'm a newbie).

Here is an example:

function wps_trend($atts) {
    extract( shortcode_atts( array(
        'w' => '500', 
        'h' => '330',
        'q' => '',
        'geo' => 'US',
    ), $atts));
    $h = (int) $h;
    $w = (int) $w;
    $q = esc_attr($geo);
    ob_start();  

Please can you explain?

Share Improve this question edited Mar 10, 2021 at 19:00 xXx 2351 silver badge4 bronze badges asked May 15, 2013 at 19:51 user28566user28566
Add a comment  | 

1 Answer 1

Reset to default 44

shortcode_atts() works like array_merge(): It merges the second list of arguments into the first one. The difference is: It merges only keys present in the first argument ($default).

extract() then takes the array keys, sets these as variable names and their values as variable values. 'w' => '500' in your example becomes $w = '500'.

Do not use extract(). This very bad code style. Its usage was deprecated even in core, and that means something … :)

Your example should be written as:

$args = shortcode_atts( 
    array(
        'w'   => '500',
        'h'   => '330',
        'q'   => '',
        'geo' => 'US',
    ), 
    $atts
);
$w = (int) $args['w'];
$h = (int) $args['h'];
$q = esc_attr( $args['q'] );
发布评论

评论列表(0)

  1. 暂无评论