Skip to content

Instantly share code, notes, and snippets.

@jonathanbossenger
Last active July 6, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanbossenger/c74e5e38eb084de47e04d63280cf1154 to your computer and use it in GitHub Desktop.
Save jonathanbossenger/c74e5e38eb084de47e04d63280cf1154 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WP Learn Dashboard Widgets
* Description: A plugin to add a widget to the dashboard
*/
add_action('wp_dashboard_setup', 'wp_learn_dashboard_widget_callback');
function wp_learn_dashboard_widget_callback(){
if (!current_user_can('manage_options')) {
return;
}
wp_add_dashboard_widget(
'wp_learn_dashboard_widget_id',
'WP Learn Dashboard Widget',
'wp_learn_dashboard_widget_content_callback',
'wp_learn_dashboard_widget_control_callback',
array(
'content' => 'This is a list of your most recent posts',
),
);
}
function wp_learn_dashboard_widget_content_callback( $screen, $widget_args ){
$number_posts = get_option( 'wp_learn_dashboard_widget_numberposts', 5 );
$post_args = array(
'numberposts' => $number_posts,
'post_status' => 'publish'
);
$recent_posts = wp_get_recent_posts( $post_args );
echo '<h3>' . $widget_args['args']['content'] . '</h3>';
echo '<ul>';
foreach( $recent_posts as $recent_post ){
echo '<li><a href="' . get_permalink( $recent_post['ID'] ) . '">' . $recent_post['post_title'] . '</a></li>';
}
echo '</ul>';
}
function wp_learn_dashboard_widget_control_callback(){
if (isset($_POST['wp_learn_dashboard_widget_numberposts'])){
update_option( 'wp_learn_dashboard_widget_numberposts', sanitize_text_field( $_POST['wp_learn_dashboard_widget_numberposts'] ) );
}
$number_posts = get_option( 'wp_learn_dashboard_widget_numberposts', 5 );
echo '<label>Enter number of posts to display</label>';
echo '<input type="text" name="wp_learn_dashboard_widget_numberposts" value='.$number_posts.' />';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment