Widgets: Use a `foreach` loop instead of The Loop to iterate over posts in Recent Posts widget to avoid needing to reset a polluted global `$post`.

Props welcher, westonruter.
Amends [14607].
See #12320.
Fixes #37312.


git-svn-id: https://develop.svn.wordpress.org/trunk@41890 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Weston Ruter 2017-10-18 00:34:01 +00:00
parent 9bca555920
commit 6c6fe52a8d
1 changed files with 26 additions and 21 deletions

View File

@ -51,8 +51,9 @@ class WP_Widget_Recent_Posts extends WP_Widget {
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
$number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5;
if ( ! $number )
if ( ! $number ) {
$number = 5;
}
$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
/**
@ -70,31 +71,35 @@ class WP_Widget_Recent_Posts extends WP_Widget {
'posts_per_page' => $number,
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true
'ignore_sticky_posts' => true,
), $instance ) );
if ($r->have_posts()) :
if ( ! $r->have_posts() ) {
return;
}
?>
<?php echo $args['before_widget']; ?>
<?php if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
} ?>
<ul>
<?php while ( $r->have_posts() ) : $r->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php get_the_title() ? the_title() : _e( '(no title)' ); ?></a>
<?php if ( $show_date ) : ?>
<span class="post-date"><?php echo get_the_date(); ?></span>
<?php endif; ?>
</li>
<?php endwhile; ?>
</ul>
<?php echo $args['after_widget']; ?>
<?php
// Reset the global $the_post as this query will have stomped on it
wp_reset_postdata();
endif;
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>
<ul>
<?php foreach ( $r->posts as $recent_post ) : ?>
<?php
$post_title = get_the_title( $recent_post->ID );
$title = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' );
?>
<li>
<a href="<?php the_permalink( $recent_post->ID ); ?>"><?php echo $title ; ?></a>
<?php if ( $show_date ) : ?>
<span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php
echo $args['after_widget'];
}
/**