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.

Built from https://develop.svn.wordpress.org/trunk@41890


git-svn-id: http://core.svn.wordpress.org/trunk@41724 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Weston Ruter 2017-10-18 00:34:46 +00:00
parent dce5306603
commit 7ee77760af
2 changed files with 27 additions and 22 deletions

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '4.9-beta2-41889';
$wp_version = '4.9-beta2-41890';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.

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 ) {
<?php
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
} ?>
}
?>
<ul>
<?php while ( $r->have_posts() ) : $r->the_post(); ?>
<?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(); ?>"><?php get_the_title() ? the_title() : _e( '(no title)' ); ?></a>
<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(); ?></span>
<span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span>
<?php endif; ?>
</li>
<?php endwhile; ?>
<?php endforeach; ?>
</ul>
<?php echo $args['after_widget']; ?>
<?php
// Reset the global $the_post as this query will have stomped on it
wp_reset_postdata();
endif;
echo $args['after_widget'];
}
/**