The code below creates to widgets on our dashboard with the title of posts from two different categories,
specified by the cat=x parameter.
// add 10 most recent post to dashboard from category with id 10
function blogPost_widget() {
$recentPosts = new WP_Query();
$recentPosts->query('showposts=10&cat=10');
?>
<ul>
<?php
while ($recentPosts->have_posts()) : $recentPosts->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php
}
//adds news widget to dashboard
function blogNews_widget() {
$recentPosts = new WP_Query();
$recentPosts->query('showposts=10&cat=1');
?>
<ul>
<?php
while ($recentPosts->have_posts()) : $recentPosts->the_post();
?>
<li><a href="<?php echo the_permalink() ?>" ><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php
}
// Create the function use in the action hook
function add_dashboard_widgets() {
//this will display titles and links to the blog posts
wp_add_dashboard_widget('blogPost_widget', 'Recent Blog Posts', 'blogPost_widget');//widget one
wp_add_dashboard_widget('blogNews_widget', 'Company news', 'blogNews_widget');//widget two
}
// Hook into the 'wp_dashboard_setup' action to register our other functions
add_action('wp_dashboard_setup', 'add_dashboard_widgets');
The above code goes into your functions.php file for a template or anywhere in your plugin file. Taken directly from the wordpress documentation, the wp_add_dashboard_widget is the magic function here,
it gives our widget an ID and a name and tells wordpress which function to invoke when creating the widget.
The parameters expected from the wordpress docs are:
<?php wp_add_dashboard_widget($widget_id, $widget_name, $callback, $control_callback ); ?>
Parameters
$widget_id
(integer) (required) an identifying slug for your widget. This will be used as its css class and its key in the array of widgets.
Default: None
$widget_name
(string) (required) this is the name your widget will display in its heading. Default: None
$callback
(string) (required) The name of a function you create that will display the actual contents of your widget. Default: None
$control_callback
(string) (optional) The name of a function you create that will handle submission of widget options forms, and will also display the form elements.