wp_media_attach_action

Encapsulate logic for Attach/Detach actions.

Description

wp_media_attach_action( (int) $parent_id, (string) $action = 'attach' ); 

Parameters (2)

0. $parent_id (int)
Attachment parent ID.
1. $action — Optional. (string) => 'attach'
Attach/detach action. Accepts attach or detach.. Default attach .

Usage

  1. if ( !function_exists( 'wp_media_attach_action' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/media.php'; 
  3.  
  4. // Attachment parent ID. 
  5. $parent_id = -1; 
  6.  
  7. // Optional. Attach/detach action. Accepts 'attach' or 'detach'. 
  8. // Default 'attach'. 
  9. $action = 'attach'; 
  10.  
  11. // NOTICE! Understand what this does before running. 
  12. $result = wp_media_attach_action($parent_id, $action); 
  13.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/media.php  
  1. function wp_media_attach_action( $parent_id, $action = 'attach' ) { 
  2. global $wpdb; 
  3.  
  4. if ( ! $parent_id ) { 
  5. return; 
  6.  
  7. if ( ! current_user_can( 'edit_post', $parent_id ) ) { 
  8. wp_die( __( 'Sorry, you are not allowed to edit this post.' ) ); 
  9. $ids = array(); 
  10. foreach ( (array) $_REQUEST['media'] as $att_id ) { 
  11. $att_id = (int) $att_id; 
  12.  
  13. if ( ! current_user_can( 'edit_post', $att_id ) ) { 
  14. continue; 
  15.  
  16. $ids[] = $att_id; 
  17.  
  18. if ( ! empty( $ids ) ) { 
  19. $ids_string = implode( ', ', $ids ); 
  20. if ( 'attach' === $action ) { 
  21. $result = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ( $ids_string )", $parent_id ) ); 
  22. } else { 
  23. $result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" ); 
  24.  
  25. foreach ( $ids as $att_id ) { 
  26. clean_attachment_cache( $att_id ); 
  27.  
  28. if ( isset( $result ) ) { 
  29. $location = 'upload.php'; 
  30. if ( $referer = wp_get_referer() ) { 
  31. if ( false !== strpos( $referer, 'upload.php' ) ) { 
  32. $location = remove_query_arg( array( 'attached', 'detach' ), $referer ); 
  33.  
  34. $key = 'attach' === $action ? 'attached' : 'detach'; 
  35. $location = add_query_arg( array( $key => $result ), $location ); 
  36. wp_redirect( $location ); 
  37. exit;