From bfe3ac37482474eb80f3636f7b82abe90443e698 Mon Sep 17 00:00:00 2001 From: Dhrupo Date: Fri, 6 Nov 2026 23:23:53 +0600 Subject: [PATCH] Error out on post term set/add when no term ID exists --- features/post-term.feature | 35 +++++++++++++++++++++++++++++++++ src/WP_CLI/CommandWithTerms.php | 8 ++++++++ 2 files changed, 43 insertions(+) diff --git a/features/post-term.feature b/features/post-term.feature index 67993d256..598dc0d42 100644 --- a/features/post-term.feature +++ b/features/post-term.feature @@ -201,6 +201,41 @@ Feature: Manage post term | term_id | name | slug | | 3 | 4 | 4 | + Scenario: Set or add terms by a term id that does not exist + Given a WP install + + When I run `wp post term add 1 post_tag apple banana` + Then STDOUT should be: + """ + Success: Added terms. + """ + + When I try `wp post term set 1 post_tag 9999 --by=id` + Then STDERR should be: + """ + Error: Could not find any term with the given ID. + """ + And STDOUT should be empty + And the return code should be 1 + + When I try `wp post term add 1 post_tag 9998 9999 --by=id` + Then STDERR should be: + """ + Error: Could not find any term with the given IDs. + """ + And STDOUT should be empty + And the return code should be 1 + + When I run `wp post term list 1 post_tag --field=slug` + Then STDOUT should contain: + """ + apple + """ + And STDOUT should contain: + """ + banana + """ + Scenario: Remove all terms from post Given a WP install diff --git a/src/WP_CLI/CommandWithTerms.php b/src/WP_CLI/CommandWithTerms.php index a70347233..47d23207d 100644 --- a/src/WP_CLI/CommandWithTerms.php +++ b/src/WP_CLI/CommandWithTerms.php @@ -258,6 +258,10 @@ public function add( $args, $assoc_args ) { $field = Utils\get_flag_value( $assoc_args, 'by' ); if ( $field ) { $terms = $this->prepare_terms( $field, $terms, $taxonomy ); + if ( ! $terms ) { + $id_label = count( $args ) > 1 ? 'IDs' : 'ID'; + WP_CLI::error( "Could not find any term with the given {$id_label}." ); + } } $result = wp_set_object_terms( $object_id, $terms, $taxonomy, true ); @@ -309,6 +313,10 @@ public function set( $args, $assoc_args ) { $field = Utils\get_flag_value( $assoc_args, 'by' ); if ( $field ) { $terms = $this->prepare_terms( $field, $terms, $taxonomy ); + if ( ! $terms ) { + $id_label = count( $args ) > 1 ? 'IDs' : 'ID'; + WP_CLI::error( "Could not find any term with the given {$id_label}." ); + } } $result = wp_set_object_terms( $object_id, $terms, $taxonomy, false );