Build your own WordPress dashboard widget for any RSS feed
It’s easy to add your own dashboard widget to WordPress, and one of the easiest to widgets to add is one that displays recent updates from any RSS feed. I put together the above widget for a project I am working on so we can promote Lawyerist posts to users.
Here’s what goes into the theme’s functions.php (or custom_functions.php, in the case of Thesis) file:
function dashboard_widget_function() {
$rss = fetch_feed( "http://lawyerist.com/feed/" );
if ( is_wp_error($rss) ) {
if ( is_admin() || current_user_can('manage_options') ) {
echo '<p>';
printf(__('<strong>RSS Error</strong>: %s'), $rss->get_error_message());
echo '</p>';
}
return;
}
if ( !$rss->get_item_quantity() ) {
echo '<p>Apparently, there are no updates to show!</p>';
$rss->__destruct();
unset($rss);
return;
}
echo "<ul>\n";
if ( !isset($items) )
$items = 5;
foreach ( $rss->get_items(0, $items) as $item ) {
$publisher = '';
$site_link = '';
$link = '';
$content = '';
$date = '';
$link = esc_url( strip_tags( $item->get_link() ) );
$title = esc_html( $item->get_title() );
$content = $item->get_content();
$content = wp_html_excerpt($content, 250) . ' ...';
echo "<li><a class='rsswidget' href='$link'>$title</a>\n<div class='rssSummary'>$content</div>\n";
}
echo "</ul>\n";
$rss->__destruct();
unset($rss);
}
function add_dashboard_widget() {
wp_add_dashboard_widget('lawyerist_dashboard_widget', 'Recent Posts from Lawyerist.com', 'dashboard_widget_function');
}
add_action('wp_dashboard_setup', 'add_dashboard_widget');
Note that there are two different functions:
- dashboard_widget_function defines the actual widget
- add_dashboard_widget adds your widget to the dashboard and gives it an id (“lawyerist_dashboard_widget”, in this case) and title (“Recent Posts from Lawyerist.com”)
To change the feed, change the URI in this line:
$rss = fetch_feed( "http://lawyerist.com/feed/" );
To change the id for the widget and the title that displays to users, change this line:
wp_add_dashboard_widget('lawyerist_dashboard_widget', 'Recent Posts from Lawyerist.com', 'lawyerist_dashboard_widget_function');
And that’s it. You’re done!
