Tuesday, July 7, 2015

Widgets: Outside My Comfort Zone

Did not take me long in WordPress to run into widgets; per the WordPress documentation:
Widgets were originally designed to provide a simple and easy-to-use way of giving design and structure control of the WordPress Theme to the user, which is now available on properly "widgetized" WordPress Themes to include the header, footer, and elsewhere in the WordPress design and structure. Widgets require no code experience or expertise. They can be added, removed, and rearranged on the WordPress Administration Appearance > Widgets panel. 
The use of widgets appears to be in conflict with my (evolving) philosophy of only using WordPress as a basic content management system; we shall see.

In order to get widgets support for a theme, one needs to implement a sidebar: https://codex.wordpress.org/Sidebars.

Extending on the Barebones theme, http://barebones-wp.blogspot.com/, we need to simply add the following:

functions.php
add_action('widgets_init','register_my_sidebars');
function register_my_sidebars() {
  register_sidebar(
    array(
      'id' => 'primary-sidebar',
      'name' => __('Primary Sidebar', 'barebones'),
      'before_widget' => '<div id="%1$s" class="%2$s">',
      'after_widget' => '</div>',
      'before_title' => '<h3>',
      'after_title' => '</h3>'
    )
  );
}

Then we implement a simple standard template file:

sidebar.php
<?php if (is_active_sidebar('primary-sidebar')) : ?>
  <?php dynamic_sidebar('primary-sidebar'); ?>
<?php endif; ?>

Then in each of the primary and secondary templates, e.g., page.php,  we need to pull in sidebar.php, e.g.,:

page.php
<?php get_sidebar(); ?>

No comments:

Post a Comment