Skip to content

Instantly share code, notes, and snippets.

@mhulse
Created June 25, 2013 19:59
Show Gist options
  • Save mhulse/5861847 to your computer and use it in GitHub Desktop.
Save mhulse/5861847 to your computer and use it in GitHub Desktop.
A more robust version of this code, and code from my original question, can be found here: https://gist.github.com/mhulse/5860561
<?php
class Foo_Widget extends WP_Widget
{
public function __construct($arr = array()) { # If I don't set a default array() value, I get this notice: "Undefined variable: arr in /.../class.foo_widget.php on line 9"
$args = wp_parse_args(
$arr,
array(
'id_base' => '',
'name' => '',
)
);
extract($args, EXTR_SKIP);
$widget_ops = array('classname' => __CLASS__, 'description' => __('Description goes here.'));
$control_ops = array('width' => 400, 'height' => 350);
# THIS WORKS:
//parent::__construct('eeeeeeeeee', 'wtf son?', $widget_ops, $control_ops);
# `$id_base` and `$name` are not getting passed:
parent::__construct($id_base, $name, $widget_ops, $control_ops); # Why doesn't this work? Is it a timing thing?
add_action(
'widgets_init',
function() {
register_widget(__CLASS__);
}
);
}
public function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['text'] = $new_instance['text']; // Unfiltered HTML.
return $instance;
}
public function form($instance) {
$instance = wp_parse_args((array) $instance, array('text' => '',));
$text = esc_textarea($instance['text']);
?>
<textarea rows="16" cols="20" name="<?=$this->get_field_name('text')?>" id="<?=$this->get_field_id('text')?>" class="widefat"><?=$text?></textarea>
<?php
}
public function widget($args, $instance) {
extract($args);
$text = apply_filters(
'widget_text',
(empty($instance['text']) ? '' : $instance['text']),
$instance
);
echo $text;
}
}
<?php
include_once('class.foo_widget.php');
$foo_test_widget = new Foo_Widget(
array(
'id_base' => 'foo_test_widget',
'name' => 'Foo Test Widget'
)
);
@JDGrimes
Copy link

So, it looks like I should just stick to the more traditional way of creating custom widgets?

Yes, I think unfortunately you'll have to stick with the traditional methods.

@mhulse
Copy link
Author

mhulse commented Jun 25, 2013

@mhulse
Copy link
Author

mhulse commented Jun 25, 2013

Yes, I think unfortunately you'll have to stick with the traditional methods.

@JDGrimes sounds good. I don't mind the traditional methods ... I just thought it might be cool to setup something similar for widgets like WPAlchemy script does for meta boxes.

Honestly, more than anything, I'm glad to know that the results I'm getting are not just a limitation of my PHP knowledge. 😄

Ok, moving on now. Thank you! 👍

@mhulse
Copy link
Author

mhulse commented Jun 26, 2013

For those interested, this is my "traditional" sidebar widget setup:

https://gist.github.com/mhulse/5864117

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment