Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wrote WordPress plugin and want to include 2 extra Widgets with it...

if( !class_exists('plugin_name') ) {
    class plugin_name {
            // plugin code
    }
}

// include widgets code
require_once( 'include/custom_functions.php' );

...and Widgets (according to WP codex) should be created like this within "custom_functions.php":

class My_Widget extends WP_Widget {
    // widget code
}
function sfp_register_widgets() {
    register_widget( 'My_Widget' );
}
add_action( 'widgets_init', 'sfp_register_widgets' );

I can't put "class SFP_Search extends WP_Widget" inside my plugin's class and if I place it outside, I get an error:

Class 'WP_Widget' not found in /Applications/XAMPP/...etc

Is there any other solution? Thanks!

share|improve this question
    
could you explain what you mean? If you're putting one class inside another class, you can't do that in php –  Mridul Aggarwal Oct 17 '12 at 11:07
1  
By default the class WP_Widget is loaded earlier than any plugin. Does your widget file run in a WordPress context, or do you call it directly? –  toscho Oct 17 '12 at 11:10
    
@MridulAggarwal - I know I can't put one class into another, I'm trying to pack widgets along with a plugin. –  Dameer Oct 17 '12 at 11:21
    
Just put the widget class before/after your plugin's main class or in a seperate file & then include it in plugin's main file. It should work without a problem –  Mridul Aggarwal Oct 17 '12 at 11:24
1  
On which hook do you include the class of your plugin? The best way is plugins_loaded. maybe you create a new instance via new Your_Class and this is to early for the class WP_Widget. –  bueltge Oct 17 '12 at 12:33
show 3 more comments

1 Answer 1

up vote 0 down vote accepted

There's no need to nest classes (and you can't anyway), you just create a new instance of the class. The code below would automatically call the My_Widget class to create a widget based on your existing code.

Class plugin_name {
        // Call the widget class
        public function __construct(){
             $this->widget = new My_Widget();
             $this->widget->getWidget();
        }
}

Class My_Widget extends WP_Widget(){
     public function getWidget(){
          //Do my widget stuff.
          echo "I'm a widget";
     }
}
share|improve this answer
add comment

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.