Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

ben pines
ben pines
8,389 Points

Is there a better way to add a widget through the theme's function.php?

I have done a custom registration form to wordpress where I ask for the user's weight. I then added this field to a widget using the theme's function.php. Is it better practice to add this code to a seperate file, and if so - how?

Here's the code to function.php:

function.php
function your_widget_display($args) {
   echo $args['before_widget'];
   echo $args['before_title'] . 'My Unique Widget' .  $args['after_title'];
   echo $args['after_widget'];
   $user_ID = get_current_user_id();
   echo esc_attr( get_user_meta( $user_ID, 'weight',true ) ); ;
}

wp_register_sidebar_widget(
    'your_widget_1',        // your unique widget id
    'Your Widget',          // widget name
    'your_widget_display',  // callback function
    array(                  // options
        'description' => 'Description of what your widget does'
    )
);
Greg Kaleka
Greg Kaleka
39,021 Points

Hi Ben,

I added formatting to your code, but I'm afraid that's as much as I can do to help! I'm not well-versed enough in WordPress.

Good luck!

-Greg

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Ben,

I did some digging, and you may find your answer in this video:

Adding Widget Areas to a WordPress Theme

Best,

-Greg