I have simple function to show an image:

function helloworld() {
    echo '<img src="'.$link.'" alt=".$alt." />';

I would like to pass strings link and alt to the function something like that:

<?php helloworld('link=www.google.com&alt=picture'); ?>

How can I achieve something like that?

  • 1
    this is really a basic PHP question - read up on how to pass argument to PHP functions. Flagged as off-topic – anu Jun 7 '11 at 13:24
  • 1
    not really a wordpress question. have you studied the php documentation, for instance: php.net/manual/en/functions.user-defined.php – Michael Jun 7 '11 at 13:25
  • parse_str is meant to parse query strings. furthermore you have to get data into your function... – kaiser Jun 7 '11 at 13:50

I agree that this is more of a basic PHP question, but I can see where you're coming from. A lot of WordPress functions accept query string formatted parameters like you're trying to do, so it would be a good idea to know exactly how they do it. Shortcode functions are guilty in particular.

First of all, you need to modify your helloworld() method to accept arguments. Then you pass them through a WordPress function that matches them against defaults. Then you'll have access to them elsewhere:

function helloworld( $args = '' ) {
    $defaults = array(
        'link' => 'www.google.com',
        'alt' = 'picture'

    wp_parse_args( $args, $defaults );

    extract( $args, EXTR_SKIP );

    echo '<img src="' . $link . '" alt="' . $alt . '" />';

Setting $args = '' in the function means that the parameter is optional. If nothing's passed in, your function will use the defaults you define instead.

So if you call helloworld('link=www.facebook.com') you'd see <img src="www.facebook.com" alt="picture" />. If you called helloworld('alt=link') you'd see <img src="www.google.com" alt="link" />. Remember, the function will use whatever you list in the $defaults array if you don't override it with something else.

The extract() function will pull out each element of the array and put it into its own variable. You don't need to do this, though. If you leave it out, you'd just referece $args['link'] instead of $link. It's really up to you.

  • Just FYI, it's bad form to downvote a post without an explanation ... – EAMann Jun 7 '11 at 15:07

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