Adding Widgets in WordPress

To add widgets in WordPress, you first need to register them in your functions.php file in your theme; this is referred to as “Registering Sidebars”. Let’s register two widgetized areas, or sidebars: one for the sidebar, and one for the footer.

function add_widgets() { register_sidebar(array( 'name' => 'Sidebar', 'id' => 'sidebar', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', )); register_sidebar(array( 'name' => 'Footer', 'id' => 'footer', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', )); } add_action('widgets_init', 'add_widgets');

The we can call the dynamic_sidebar function in the sidebar and footer.

<?php if (is_active_sidebar('sidebar')) : ?> <aside class="sidebar"> <?php dynamic_sidebar('sidebar'); ?> </aside> <?php endif; ?>

<?php if (is_active_sidebar('footer')) : ?> <footer class="footer"> <?php dynamic_sidebar('footer'); ?> </footer> <?php endif; ?>

And now you can dynamically add and remove widgets from your WordPress admin area, under Appearance > Widgets.

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"