WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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
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
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();

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

Your Answer


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.