Monday, March 16, 2009

Adding Widgets to Your WordPress Dashboard

Well, first off, I take no credit for most of this information you're about to read. I just tweaked the code I got from wpengineer.com, so go check out that site for the original details.

Anyhow, we're recently in the process of beta'ing WordPress 2.7 (from 2.0.1). We wrote a lot of custom code on top of WordPress already and most of it worked with little or no help. One of the recent complaints from one of our test users was regarding the new dashboard and the lack of "recent posts" and "scheduled posts".

If you haven't used WordPress 2.0.1, well there used to be a list of recent published posts and scheduled posts right on the dashboard. Honestly, in 2.7 the data is still there, just a few more clicks away. But anyway, to please our users, I wrote this plugin to add two widgets, "My Recent Posts" and "My Scheduled Posts".

It's loosely called "AddDashboard" for now. I'll try and come up with something snazzier later.

Enjoy. Cheers!

post script: I've "escaped" some of the code such as: <\?php


<\?php
/*
Plugin Name: AddDashboard
Plugin URI:
Description: This plugin adds on to the WP Dashboard
Version: 0.1
Author: Adrian J. Cruz
Author URI:
License:
Changelog:
*/


/**
* Content of Dashboard-Widget
*/
function my_wp_dashboard_recent() {
$result = get_recent_posts(10, publish);
if (!$result) { echo 'No recent posts.'; }
else {
foreach($result as $key => $value) {
print "<\a href=\"post.php?action=edit&post=" . $value['ID'] . "\">"
. $value['ID'] . ": " . $value['post_title'] . "<\/a>
";
}
}
}

function my_scheduled_posts() {
$result = get_recent_posts(10, future);
if (!$result) { echo 'No posts scheduled to be published.'; }
else {
foreach($result as $key => $value) {
print "<\a href=\"post.php?action=edit&post=" . $value['ID'] . "\">"
. $value['ID'] . ": " . $value['post_title'] . "<\/a>
";
}
}
}

/**
* add Dashboard Widget via function wp_add_dashboard_widget()
*/
function my_wp_dashboard_setup() {
wp_add_dashboard_widget( 'my_wp_dashboard_recent', __( 'My Recent Posts' ), 'my_wp_dashboard_recent' );
}

function my_scheduled_posts_setup() {
wp_add_dashboard_widget( 'my_scheduled_posts', __( 'My Scheduled Posts' ), 'my_scheduled_posts' );
}

/**
* use hook, to integrate new widget
*/
add_action('wp_dashboard_setup', 'my_wp_dashboard_setup');
add_action('wp_dashboard_setup', 'my_scheduled_posts_setup');

function get_recent_posts($num = 10, $status) {
global $wpdb;

// Set the limit clause, if we got a limit
$num = (int) $num;
if ($num) {
$limit = "LIMIT $num";
}
// if no $status default to publish
if (!status) {
$status = "publish";
}

$sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status='$status' ORDER BY post_date DESC $limit";
$result = $wpdb->get_results($sql,ARRAY_A);

return $result ? $result : array();
}
?>

No comments: