Skip to content

Commit 9bc4e2f

Browse files
Taxonomy: Check the result of get_term() in WP_Term_Query::get_terms().
`get_term()` can return `WP_Error` or `null` on failure, so the result should be verified as a `WP_Term` instance before accessing the `count` property. This commit prevents a PHP warning if `get_term()` returns `null` for a child term: {{{ Warning: Attempt to read property "count" on null }}} Follow-up to [27458], [37572]. Props josephscott, coleatkinson1, kebbet, jakariaistauk, sabernhardt, westonruter, SergeyBiryukov. Fixes #63877. git-svn-id: https://develop.svn.wordpress.org/trunk@60661 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 06aca12 commit 9bc4e2f

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/wp-includes/class-wp-term-query.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -849,7 +849,8 @@ public function get_terms() {
849849
if ( is_array( $children ) ) {
850850
foreach ( $children as $child_id ) {
851851
$child = get_term( $child_id, $term->taxonomy );
852-
if ( $child->count ) {
852+
853+
if ( $child instanceof WP_Term && $child->count ) {
853854
continue 2;
854855
}
855856
}

tests/phpunit/tests/term/query.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,53 @@ public function test_null_term_object_should_be_discarded() {
852852
$this->assertSameSets( $expected, wp_list_pluck( $found, 'term_id' ) );
853853
}
854854

855+
/**
856+
* Tests that a call to WP_Term_Query::get_terms() does not result in a PHP warning
857+
* when get_term() returns null for a child term.
858+
*
859+
* The warning that we should not see:
860+
* `Warning: Attempt to read property "count" on null`.
861+
*
862+
* @ticket 63877
863+
*/
864+
public function test_null_child_term_should_not_throw_warning() {
865+
register_taxonomy(
866+
'wptests_tax',
867+
'post',
868+
array(
869+
'hierarchical' => true,
870+
)
871+
);
872+
873+
$t1 = self::factory()->term->create(
874+
array(
875+
'taxonomy' => 'wptests_tax',
876+
)
877+
);
878+
879+
$t2 = self::factory()->term->create(
880+
array(
881+
'taxonomy' => 'wptests_tax',
882+
'parent' => $t1,
883+
)
884+
);
885+
886+
$this->term_id = $t2;
887+
888+
add_filter( 'get_term', array( $this, 'filter_term_to_null' ) );
889+
$q = new WP_Term_Query(
890+
array(
891+
'taxonomy' => 'wptests_tax',
892+
'hide_empty' => true,
893+
'fields' => 'ids',
894+
)
895+
);
896+
remove_filter( 'get_term', array( $this, 'filter_term_to_null' ) );
897+
898+
$this->assertIsArray( $q->terms, 'The result should be an array.' );
899+
$this->assertEmpty( $q->terms, 'The result should be empty.' );
900+
}
901+
855902
public function filter_term_to_null( $term ) {
856903
if ( $this->term_id === $term->term_id ) {
857904
return null;

0 commit comments

Comments
 (0)