Search code examples
phpwordpresswidgetfooterwordpress-plugin-creation

How to create custom widget area and store content in footer?


I want to craete a custom widget area and store it's content in footer.

I'm doing this as a part of the plugin I'm creating. So, in the main plugin file, I tried with:

 if ( function_exists('register_sidebar') )
 register_sidebar(array(
'name' => 'Name of Widgetized Area',
'before_widget' => '<div class = "widgetizedArea">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
)
);

but it doesn't showing the widget area in wordpress admin Appearance -> Widgets.

That's the first problem... The other one is: When I figure out how to add a widget area, then how to implement that the widget stored in that custom widget area be placed in footer? I'm thinking of adding this to footer.php file of the theme I'm using:

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Name of 
Widgetized Area") ) : ?>
<?php endif;?>

I'm not sure that this is right... and another problem is: I'm adding this directly in footer.php of a theme I'm using, so it means that the plugin will not work if another theme is installed and activated. Should I write a function to find footer.php file and then write that in it or should I do something else. And what if a theme doesn't have footer.php file?


Solution

  • There are two ways to add widgets: 1) Using Widgets on Page plugin 2) You can add widget using code.

    1) You can directly install Widgets on page plugin. There you can easily create a plugin. I will be display in widgets, and it will generate a shortcode which you can place it in footer.php or any other file where you want to display your widget

    2) You can create you widget area using below code: Add this code to your theme funtion.php

     function arphabet_widgets_init() {
    
        register_sidebar( array(
            'name'          => 'Home right sidebar',
            'id'            => 'home_right_1',
            'before_widget' => '<div>',
            'after_widget'  => '</div>',
            'before_title'  => '<h2 class="rounded">',
            'after_title'   => '</h2>',
        ) );
    }
    add_action( 'widgets_init', 'arphabet_widgets_init' );
    

    and then add this code to your footer.php

    <?php if ( is_active_sidebar( 'home_right_1' ) ) : ?>
        <div id="primary-sidebar" class="primary-sidebar widget-area" role="complementary">
            <?php dynamic_sidebar( 'home_right_1' ); ?>
        </div><!-- #primary-sidebar -->
    <?php endif; ?>
    

    This is the function which outputs the widget:

    <?php dynamic_sidebar( 'home_right_1' ); ?>
    

    Hope this will help you..