[wp-trac] [WordPress Trac] #41035: Don't return if WP_Error object return by wp_insert_term() from foreach() loop in wp_set_object_terms()

WordPress Trac noreply at wordpress.org
Tue Jun 13 20:57:31 UTC 2017


#41035: Don't return if WP_Error object return by wp_insert_term() from foreach()
loop in wp_set_object_terms()
----------------------------+-----------------------------
 Reporter:  chandrapatel    |      Owner:
     Type:  defect (bug)    |     Status:  new
 Priority:  normal          |  Milestone:  Awaiting Review
Component:  Taxonomy        |    Version:  4.7
 Severity:  normal          |   Keywords:
  Focuses:  administration  |
----------------------------+-----------------------------
 Recently, I'm trying to restrict tag creation for some user roles. I tried
 with using roles and capabilities but it's not possible. So I hook
 function to `pre_insert_term` filter which returns WP_Error object if
 condition match.
 {{{
 add_action( 'pre_insert_term', 'prevent_terms', 1, 2 );

 function prevent_terms ( $term, $taxonomy ) {

         if ( 'post_tag' !== $taxonomy ) {
                 return $term;
         }

          // Only administrator can create tag.
         $allowed_roles = array( 'administrator' );

         $user = wp_get_current_user();

         if ( ! empty( $user->roles ) && empty( array_intersect(
 $allowed_roles, $user->roles ) ) ) {

                 return new WP_Error( 'term_addition_blocked', 'You are not
 allowed to create new tags.' );

         }

         return $term;

 }
 }}}


 Now, a restricted user goes to the edit post and trying to assign existing
 tags to the post and its work fine. But when a user adds a tag which does
 not exist along with existing tags then existing tags also not assigned to
 that post. Because `wp_set_object_terms()` function will create new tag if
 it's not exists and I've return WP_Error object using `pre_insert_term`
 hook. So once it get WP_Error object then it returns from the
 `wp_set_object_terms()` function and it's also not execute for other
 terms.

 See https://core.trac.wordpress.org/browser/tags/4.8/src/wp-
 includes/taxonomy.php#L2237

 To complete my functionality I hook into `admin_init` action and remove
 new tags from $_POST so that remaining existing tags can assign to the
 post.

 I believe, instead of returning, it should continue execution for other
 terms. Also, I'm not sure whether it's valid use case or not.

 So main question is, do we need to return if there is WP_Error while
 creating term or don't return and continue execution for other terms.

 I hope, I'm able to explain it properly. :)

--
Ticket URL: <https://core.trac.wordpress.org/ticket/41035>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list