I’m running WordPress 3.1.3, and am looking to create a sidebar widget which more-or-less counts down to a recurring event. I’ve got the underlying PHP code for the countdown working in a standalone script, but where I’m having trouble is actually “widget-izing” the code, because it contains references to other functions.
Here’s a distilled version of what I have (not including the required plugin header, etc.):
add_action("widgets_init", array('LMC_countdown', 'register'));
class LMC_countdown extends WP_Widget {
function control(){
echo "This widget doesn't need a control panel in WordPress right now.";
# In all likelihood, that'll be a separate issue for later. :)
}
function widget($args){
echo $args['before_widget'];
# //////////////////// BEGIN MAIN WIDGET FUNCTION ////////////////////
$year = date("Y",$today);
echo "<div id="sidebar-countdown">";
/* ...
quite a bit of additional PHP logic here, but boils down to:
*/
echo countdownTo(findEventStart($year));
echo "</div>";
# //////////////////// END MAIN WIDGET FUNCTION ////////////////////
echo $args['after_widget'];
}
function register(){
register_sidebar_widget('LMC Countdown', array('LMC_countdown', 'widget'));
register_widget_control('LMC Countdown', array('LMC_countdown', 'control'));
}
} # end class LMC_countdown
The issue, of course, is that countdownTo()
and findEventStart()
are custom functions which “support” the main widget action, which themselves call a few other “supporting functions.” Wherever I’ve tried putting these supporting functions â whether in the class after register()
or within the widget()
function itself â I keep getting errors that the first of these functions is undefined.
I got most of my structural code for the widget from tutorials and “Hello world” examples, but none are robust enough to have PHP functions nestled within them. So where should I be putting these “supporting functions” and how should I be calling them within the widget? Thanks in advance for your help.
Place those two functions below the class. Then they are available inside the class as well.
You have written them a global functions, so they belong outside the class. They will be available to your widget and any other plugin / script. So it’s a good idea you prefix their names as well with
LMC_
.Another way you could do is to add them into the class. All of the class’s functions are accesible via
$this
inside the class: