0

I'm working on my first shortcode, examples in Shortcode API are not suitable for starters, so I'm almost sure I'm doing it wrong!

My shortcode:

function hello( $atts ) {
        extract( shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
        ), $atts ) );

       return 'Hello, World!';
       return $foo;
   }

add_shortcode('hw', 'hello');

And I want [hw foo=HEHEHE] to output: Hello, World! HEHEHE.

But it displays only Hello, World!

How to access & echo shortcode attributes and eventually how to set the default value (I guess I've already set the default values to "something" and "something else" but I'm not sure since I have no idea how to output them.

3 Answers 3

2

You are return two times! The first return exit the function, so your shortcode outputs always "Hello World".

Correct code:

function hello( $atts ) {
    extract( shortcode_atts( array(
    'foo' => 'something',
    'bar' => 'something else',
    ), $atts ) );

   print_r($atts); // Remove, when you are fine with your atts! 
   return 'Hello, World: '.$atts['foo'];

}
 add_shortcode('hw', 'hello');

For the second question: do a print_r($atts) after the extracts part!

1
  • 2
    This answer is not correct, the use of extract() and $atts is inconsistent. The extract() function creates variables called $foo and $bar and these should be used in the return statement instead of $atts. Either that, or do not use extract() at all and do: $atts = shortcode_atts(.....) instead Apr 12, 2014 at 11:09
2

This should do it:

    function hello( $atts ) {

        extract( shortcode_atts( array(
                                     'foo' => 'Default'
                                     ), $atts ) );
        return 'Hello, World! ' . $foo . '.';

    }

add_shortcode('hw', 'hello');

If no value for foo is passed in it sets the default value of 'Default'.

The return line returns the words 'hello world' followed by the contents of foo then a full stop.

1
  • This is the correct answer as it actually uses the output of the extract() function correctly. I.e. is uses $foo in the return statement, which was created by the call to extract(). Apr 12, 2014 at 11:02
1

you shortcode function is just fine but since you return first return 'Hello, World!'; the function ends before running return $foo; if you want you can change it a bit to see attributes :

function hello( $atts ) {
        extract( shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
        ), $atts ) );

       return 'Hello, World! Foo: ' . $atts['foo'] ;

   }

add_shortcode('hw', 'hello');

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.