Skip to content

Instantly share code, notes, and snippets.

@markoheijnen
Created May 1, 2012 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markoheijnen/2572299 to your computer and use it in GitHub Desktop.
Save markoheijnen/2572299 to your computer and use it in GitHub Desktop.
Adding post type to the Recent post widget to WordPress 3.4+
<?php
add_action( 'in_widget_form', 'extend_recent_posts_form', 10, 3 );
add_filter( 'widget_update_callback', 'extend_recent_posts_update', 10, 4 );
add_filter( 'widget_title', 'extend_recent_posts_init_query_filter', 10, 3 );
add_filter( 'widget_posts_args', 'extend_recent_posts_query' );
function extend_recent_posts_form( $widget, $return, $instance ) {
if( ! is_a( $widget, 'WP_Widget_Recent_Posts' ) )
return;
echo '<select id="' . $widget->get_field_id('posttype') . '" name="' . $widget->get_field_name('posttype') . '" >';
$post_types = get_post_types( array( 'show_ui' => true ) );
foreach ( $post_types as $post_type ) {
if( $post_type == $instance['post_type'] ) {
echo '<option selected="selected">' . $post_type . '</option>';
}
else {
echo '<option>' . $post_type . '</option>';
}
}
echo '</select>';
}
function extend_recent_posts_update( $instance, $new_instance, $old_instance, $widget ) {
if( ! is_a( $widget, 'WP_Widget_Recent_Posts' ) )
return $instance;
$post_type = strip_tags( $new_instance['posttype'] );
if( post_type_exists( $post_type ) ) {
$instance['post_type'] = $post_type;
}
return $instance;
}
// $title, $instance, $id_base
function extend_recent_posts_init_query_filter( $title ) {
global $recent_posts_posttype;
if( func_num_args() >= 3 ) {
$instance = func_get_arg( 1 );
$id_base = func_get_arg( 2 );
if( isset( $instance['post_type'] ) && 'recent-posts' == $id_base ) {
$recent_posts_posttype = $instance['post_type'];
}
}
return $title;
}
function extend_recent_posts_query( $vars ) {
global $recent_posts_posttype;
if( ! empty( $recent_posts_posttype ) ) {
$vars['post_type'] = $recent_posts_posttype;
$recent_posts_posttype = '';
}
return $vars;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment