0

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!

8
  • could you explain what you mean? If you're putting one class inside another class, you can't do that in php Commented Oct 17, 2012 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?
    – fuxia
    Commented Oct 17, 2012 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
    Commented Oct 17, 2012 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 Commented Oct 17, 2012 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
    Commented Oct 17, 2012 at 12:33

2 Answers 2

0

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";
     }
}
0

if you are inside namespaced file, you should use slash in front of any global class:

class My_Widget extends \WP_Widget {
    ...
}

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.