Display Any Native WordPress Widget Anywhere in Your Theme

Found this handy little function the_widget which you may find useful at some stage.

There’s at least 2 ways to use the function which is normally the case, (1)either add the template directly to your template file or (2)include it in a custom function from your functions.php file.

Here’s the default usage for direct use in template files which includes 3 parameters.

<?php the_widget( $widget, $instance, $args ); ?>

The first parameter, $widget, should be replaced with the PHP class name of the widget.

You can grab any of the native WordPress widget classes directly from the default-widgets.php file in the WordPress core files.

<?php the_widget( 'WP_Widget_Archives', $instance, $args ); ?>

Here’s the most basic usage of the template tag:

<?php the_widget( 'WP_Widget_Archives' ); ?>

You can also use the_widget function in custom functions with hooks and conditional tags.

Here’s an example of the most basic usage in a custom function:

And here’s an example of using the same widget class with all parameters for the function the widget uses which in this case is the wp_get_archives function.


Comments

2 responses to “Display Any Native WordPress Widget Anywhere in Your Theme”

  1. Great post as usual but I have a question.

    I have been using custom menus in sidebar widgets, each page having its own sidebar menu. However, with mobile, the menu goes down below the content. If I am understanding correctly I could use WP_Nav_Menu_Widget to display a menu in the content area in the first column so it stays on top?

    If so how do I choose which menu I want to display on the different pages?

    1. Brad Dalton Avatar
      Brad Dalton

      Thanks Lynne.

      Conditional tags or custom fields if you want alot of different menus.

      I think you can also rig the Genesis Simple Sidebars plugin to display in different hook positions.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.