_fix_attachment_links

Replace hrefs of attachment anchors with up-to-date permalinks.

Description

(void|int|WP_Error) _fix_attachment_links( (int|object) $post ); 

Returns (void|int|WP_Error)

Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.

Parameters (1)

0. $post (int|object)
Post ID or post object.

Usage

  1. if ( !function_exists( '_fix_attachment_links' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/post.php'; 
  3.  
  4. // Post ID or post object. 
  5. $post = null; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = _fix_attachment_links($post); 
  9.  

Defined (1)

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

/wp-admin/includes/post.php  
  1. function _fix_attachment_links( $post ) { 
  2. $post = get_post( $post, ARRAY_A ); 
  3. $content = $post['post_content']; 
  4.  
  5. // Don't run if no pretty permalinks or post is not published, scheduled, or privately published. 
  6. if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) ) 
  7. return; 
  8.  
  9. // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero) 
  10. if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) ) 
  11. return; 
  12.  
  13. $site_url = get_bloginfo('url'); 
  14. $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s) 
  15. $replace = ''; 
  16.  
  17. foreach ( $link_matches[1] as $key => $value ) { 
  18. if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-') 
  19. || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match ) 
  20. || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) ) 
  21. continue; 
  22.  
  23. $quote = $url_match[1]; // the quote (single or double) 
  24. $url_id = (int) $url_match[2]; 
  25. $rel_id = (int) $rel_match[1]; 
  26.  
  27. if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false ) 
  28. continue; 
  29.  
  30. $link = $link_matches[0][$key]; 
  31. $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link ); 
  32.  
  33. $content = str_replace( $link, $replace, $content ); 
  34.  
  35. if ( $replace ) { 
  36. $post['post_content'] = $content; 
  37. // Escape data pulled from DB. 
  38. $post = add_magic_quotes($post); 
  39.  
  40. return wp_update_post($post);