35

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?

1 Answer 1

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'] );
3
  • 1
    Thank-you. I didn't know about the extract, so thanks for that too! Commented May 15, 2013 at 20:07
  • 7
    extract() is also discouraged by WP coding standards. See make.wordpress.org/core/handbook/best-practices/… Commented Feb 17, 2016 at 9:38
  • Warning! Do not use extract() on untrusted data, like user input. Is unsecure and you can made a lot of conflicts and also overwritte some codes what you have before. That only can be used in some realy, realy, realy protected part of code where you will know what expected and what you need. Commented Apr 13, 2017 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.