Guest User

Add Credit URL to images and photos in WordPress

a guest
Oct 16th, 2011
1,157
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. add_filter("attachment_fields_to_edit", "add_image_source_url", 10, 2);
  3. function add_image_source_url($form_fields, $post) {
  4.     $form_fields["source_url"] = array(
  5.         "label" => __("Source URL"),
  6.         "input" => "text",
  7.         "value" => get_post_meta($post->ID, "source_url", true),
  8.                 "helps" => __("Add the URL where the original image was posted"),
  9.     );
  10.     return $form_fields;
  11. }
  12.  
  13. add_filter("attachment_fields_to_save", "save_image_source_url", 10 , 2);
  14. function save_image_source_url($post, $attachment) {
  15.     if (isset($attachment['source_url']))
  16.         update_post_meta($post['ID'], 'source_url', trim($attachment['source_url']));
  17.     return $post;
  18. }
  19.  
  20. add_filter('img_caption_shortcode', 'caption_shortcode_with_credits', 10, 3);
  21. function caption_shortcode_with_credits($empty, $attr, $content) {
  22.     extract(shortcode_atts(array(
  23.         'id'    => '',
  24.         'align' => 'alignnone',
  25.         'width' => '',
  26.         'caption' => ''
  27.     ), $attr));
  28.    
  29.     // Extract attachment $post->ID
  30.     preg_match('/\d+/', $id, $att_id);
  31.     if (is_numeric($att_id[0]) && $source_url = get_post_meta($att_id[0], 'source_url', true)) {
  32.         if (!strstr($source_url, 'http://'))
  33.             $source_url = 'http://' . $source_url;
  34.         $parts = parse_url($source_url);
  35.         $caption .= ' ('. __('via') .' <a href="'. $source_url .'">'. $parts['host'] .'</a>)';
  36.     }
  37.  
  38.     if ( 1 > (int) $width || empty($caption) )
  39.         return $content;
  40.  
  41.     if ( $id )
  42.         $id = 'id="' . esc_attr($id) . '" ';
  43.  
  44.     return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
  45.     . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
  46. }
  47.  
RAW Paste Data