Skip to content

Commit 8f3f3a0

Browse files
Code Modernization: Fix "passing null to non-nullable" deprecation from previous_posts().
The `esc_url()` function expects to a string for `$url` parameter. There is no input validation within that function. The function contains a `ltrim()` which also expects a string. Passing `null` to this parameter results in `Deprecated: ltrim(): Passing null to parameter #1 ($string) of type string is deprecated` notice on PHP 8.1+. Tracing the stack back, a `null` is being passed to it within `previous_posts()` when `get_previous_posts_page_link()` returns `null` (it can return a string or `null`). On PHP 7.0 to PHP 8.x, an empty string is returned from `esc_url()` when `null` is passed to it. The change in this changeset avoids the deprecation notice by not invoking `esc_url()` when `get_previous_posts_page_link()` returns `null` and instead sets the `$output` to an empty string, thus maintaining the same behavior as before (minus the deprecation notice). Adds a test to validate an empty string is returned and the absence of the deprecation (when running on PHP 8.1+). Follow-up to [9632], [11383], [56740]. Props dd32, alexodiy. Fixes #64864. git-svn-id: https://develop.svn.wordpress.org/trunk@62034 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 0f8e84c commit 8f3f3a0

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/wp-includes/link-template.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2649,7 +2649,8 @@ function get_previous_posts_page_link() {
26492649
* @return string|null The previous posts page link if `$display = false`.
26502650
*/
26512651
function previous_posts( $display = true ) {
2652-
$output = esc_url( get_previous_posts_page_link() );
2652+
$link = get_previous_posts_page_link();
2653+
$output = $link ? esc_url( $link ) : '';
26532654

26542655
if ( $display ) {
26552656
echo $output;
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
/**
4+
* Tests the `previous_posts()` function.
5+
*
6+
* @since 7.0.0
7+
*
8+
* @group link
9+
*
10+
* @covers ::previous_posts
11+
*/
12+
class Tests_Link_PreviousPosts extends WP_UnitTestCase {
13+
14+
/**
15+
* The absence of a deprecation notice on PHP 8.1+ also shows that the issue is resolved.
16+
*
17+
* @ticket 64864
18+
*/
19+
public function test_should_return_empty_string_on_singular() {
20+
$post_id = self::factory()->post->create();
21+
$this->go_to( get_permalink( $post_id ) );
22+
23+
$this->assertSame( '', previous_posts( false ) );
24+
}
25+
}

0 commit comments

Comments
 (0)