Variable doesn’t exist outside of the function?

you’re going to see WordPress Widget code (a bit modified taken from Akismet).

The problem is $title; variable works fine only in one function and globals etc. doesn’t seem to help here.

Read More

What’s wrong?

 function myWidget_control() {
        $options = $newoptions = get_option('myWidget');

        if ( isset( $_POST['myWidget-submit'] ) && $_POST["myWidget-submit"] ) {
            $newoptions['title'] = strip_tags(stripslashes($_POST["myWidget-title"]));
            if ( empty($newoptions['title']) ) $newoptions['title'] = __('Spam Blocked');
        }

        if ( $options != $newoptions ) {
            $options = $newoptions;
            update_option('myWidget', $options);
        }

        $title = htmlspecialchars($options['title'], ENT_QUOTES); ?>

                <p><label for="myWidget-title"><?php _e('Title:');  ?><input style="width: 250px;" id="myWidget-title" name="myWidget-title" type="text" value="<?php echo $title; ?>" /></label></p>
                <input type="hidden" id="myWidget-submit" name="myWidget-submit" value="1" />

<?php 
}
function myWidget()
{

   echo $title; /* shows nothing but works perfectly 8 lines above! */
   echo $options['title']; /* shows nothing once again */
}

Related posts

Leave a Reply

3 comments

  1. $title is defined within the scope of the myWidget_control() function, so is available only there.

    If you need it to be available in myWidget() it must be created/retrieved there too, I would suggest calling get_option(‘myWidget’) again to retrieve it.

    function myWidget() {
       $options = get_option('myWidget');
       $title = htmlspecialchars($options['title'], ENT_QUOTES);
    
       echo $title;
    }
    
  2. Those variables are defined within the function itself and thus cannot be accessed outside of those functions unless you tell them to. Give globalling them a try…

    function myWidget_control() {
         global $title, $options;
         [yourcode]
    }
    function myWidget() {
         global $title, $options;
    
       echo $title;
       echo $options['title'];
    

    }

    You might not need to global them within both functions, but I think you do.