Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

3 Answers

up vote 1 down vote accepted

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!

share|improve this answer

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.

share|improve this answer

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');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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