PageRenderTime 36ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/media.php

https://github.com/yanickouellet/WordPress
PHP | 2528 lines | 1344 code | 340 blank | 844 comment | 323 complexity | acae13dabe7b5169ca5b8a88946f9a6a MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. * @subpackage Media
  7. */
  8. /**
  9. * Scale down the default size of an image.
  10. *
  11. * This is so that the image is a better fit for the editor and theme.
  12. *
  13. * The $size parameter accepts either an array or a string. The supported string
  14. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  15. * 128 width and 96 height in pixels. Also supported for the string value is
  16. * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
  17. * than the supported will result in the content_width size or 500 if that is
  18. * not set.
  19. *
  20. * Finally, there is a filter named 'editor_max_image_size', that will be called
  21. * on the calculated array for width and height, respectively. The second
  22. * parameter will be the value that was in the $size parameter. The returned
  23. * type for the hook is an array with the width as the first element and the
  24. * height as the second element.
  25. *
  26. * @since 2.5.0
  27. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  28. *
  29. * @param int $width Width of the image
  30. * @param int $height Height of the image
  31. * @param string|array $size Size of what the result image should be.
  32. * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
  33. * @return array Width and height of what the result image should resize to.
  34. */
  35. function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
  36. global $content_width, $_wp_additional_image_sizes;
  37. if ( ! $context )
  38. $context = is_admin() ? 'edit' : 'display';
  39. if ( is_array($size) ) {
  40. $max_width = $size[0];
  41. $max_height = $size[1];
  42. }
  43. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  44. $max_width = intval(get_option('thumbnail_size_w'));
  45. $max_height = intval(get_option('thumbnail_size_h'));
  46. // last chance thumbnail size defaults
  47. if ( !$max_width && !$max_height ) {
  48. $max_width = 128;
  49. $max_height = 96;
  50. }
  51. }
  52. elseif ( $size == 'medium' ) {
  53. $max_width = intval(get_option('medium_size_w'));
  54. $max_height = intval(get_option('medium_size_h'));
  55. // if no width is set, default to the theme content width if available
  56. }
  57. elseif ( $size == 'large' ) {
  58. // We're inserting a large size image into the editor. If it's a really
  59. // big image we'll scale it down to fit reasonably within the editor
  60. // itself, and within the theme's content width if it's known. The user
  61. // can resize it in the editor if they wish.
  62. $max_width = intval(get_option('large_size_w'));
  63. $max_height = intval(get_option('large_size_h'));
  64. if ( intval($content_width) > 0 )
  65. $max_width = min( intval($content_width), $max_width );
  66. } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  67. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  68. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  69. if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
  70. $max_width = min( intval($content_width), $max_width );
  71. }
  72. // $size == 'full' has no constraint
  73. else {
  74. $max_width = $width;
  75. $max_height = $height;
  76. }
  77. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  78. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  79. }
  80. /**
  81. * Retrieve width and height attributes using given width and height values.
  82. *
  83. * Both attributes are required in the sense that both parameters must have a
  84. * value, but are optional in that if you set them to false or null, then they
  85. * will not be added to the returned string.
  86. *
  87. * You can set the value using a string, but it will only take numeric values.
  88. * If you wish to put 'px' after the numbers, then it will be stripped out of
  89. * the return.
  90. *
  91. * @since 2.5.0
  92. *
  93. * @param int|string $width Optional. Width attribute value.
  94. * @param int|string $height Optional. Height attribute value.
  95. * @return string HTML attributes for width and, or height.
  96. */
  97. function image_hwstring($width, $height) {
  98. $out = '';
  99. if ($width)
  100. $out .= 'width="'.intval($width).'" ';
  101. if ($height)
  102. $out .= 'height="'.intval($height).'" ';
  103. return $out;
  104. }
  105. /**
  106. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  107. *
  108. * Array with image url, width, height, and whether is intermediate size, in
  109. * that order is returned on success is returned. $is_intermediate is true if
  110. * $url is a resized image, false if it is the original.
  111. *
  112. * The URL might be the original image, or it might be a resized version. This
  113. * function won't create a new resized copy, it will just return an already
  114. * resized one if it exists.
  115. *
  116. * A plugin may use the 'image_downsize' filter to hook into and offer image
  117. * resizing services for images. The hook must return an array with the same
  118. * elements that are returned in the function. The first element being the URL
  119. * to the new image that was resized.
  120. *
  121. * @since 2.5.0
  122. * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide
  123. * resize services.
  124. *
  125. * @param int $id Attachment ID for image.
  126. * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
  127. * @return bool|array False on failure, array on success.
  128. */
  129. function image_downsize($id, $size = 'medium') {
  130. if ( !wp_attachment_is_image($id) )
  131. return false;
  132. // plugins can use this to provide resize services
  133. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) )
  134. return $out;
  135. $img_url = wp_get_attachment_url($id);
  136. $meta = wp_get_attachment_metadata($id);
  137. $width = $height = 0;
  138. $is_intermediate = false;
  139. $img_url_basename = wp_basename($img_url);
  140. // try for a new style intermediate size
  141. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  142. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  143. $width = $intermediate['width'];
  144. $height = $intermediate['height'];
  145. $is_intermediate = true;
  146. }
  147. elseif ( $size == 'thumbnail' ) {
  148. // fall back to the old thumbnail
  149. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  150. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  151. $width = $info[0];
  152. $height = $info[1];
  153. $is_intermediate = true;
  154. }
  155. }
  156. if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
  157. // any other type: use the real image
  158. $width = $meta['width'];
  159. $height = $meta['height'];
  160. }
  161. if ( $img_url) {
  162. // we have the actual image size, but might need to further constrain it if content_width is narrower
  163. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  164. return array( $img_url, $width, $height, $is_intermediate );
  165. }
  166. return false;
  167. }
  168. /**
  169. * Registers a new image size
  170. *
  171. * @since 2.9.0
  172. */
  173. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  174. global $_wp_additional_image_sizes;
  175. $_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
  176. }
  177. /**
  178. * Registers an image size for the post thumbnail
  179. *
  180. * @since 2.9.0
  181. */
  182. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  183. add_image_size( 'post-thumbnail', $width, $height, $crop );
  184. }
  185. /**
  186. * An <img src /> tag for an image attachment, scaling it down if requested.
  187. *
  188. * The filter 'get_image_tag_class' allows for changing the class name for the
  189. * image without having to use regular expressions on the HTML content. The
  190. * parameters are: what WordPress will use for the class, the Attachment ID,
  191. * image align value, and the size the image should be.
  192. *
  193. * The second filter 'get_image_tag' has the HTML content, which can then be
  194. * further manipulated by a plugin to change all attribute values and even HTML
  195. * content.
  196. *
  197. * @since 2.5.0
  198. *
  199. * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element
  200. * class attribute.
  201. * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with
  202. * all attributes.
  203. *
  204. * @param int $id Attachment ID.
  205. * @param string $alt Image Description for the alt attribute.
  206. * @param string $title Image Description for the title attribute.
  207. * @param string $align Part of the class name for aligning the image.
  208. * @param string $size Optional. Default is 'medium'.
  209. * @return string HTML IMG element for given image attachment
  210. */
  211. function get_image_tag($id, $alt, $title, $align, $size='medium') {
  212. list( $img_src, $width, $height ) = image_downsize($id, $size);
  213. $hwstring = image_hwstring($width, $height);
  214. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  215. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  216. $class = apply_filters('get_image_tag_class', $class, $id, $align, $size);
  217. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  218. $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  219. return $html;
  220. }
  221. /**
  222. * Calculates the new dimensions for a downsampled image.
  223. *
  224. * If either width or height are empty, no constraint is applied on
  225. * that dimension.
  226. *
  227. * @since 2.5.0
  228. *
  229. * @param int $current_width Current width of the image.
  230. * @param int $current_height Current height of the image.
  231. * @param int $max_width Optional. Maximum wanted width.
  232. * @param int $max_height Optional. Maximum wanted height.
  233. * @return array First item is the width, the second item is the height.
  234. */
  235. function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
  236. if ( !$max_width and !$max_height )
  237. return array( $current_width, $current_height );
  238. $width_ratio = $height_ratio = 1.0;
  239. $did_width = $did_height = false;
  240. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  241. $width_ratio = $max_width / $current_width;
  242. $did_width = true;
  243. }
  244. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  245. $height_ratio = $max_height / $current_height;
  246. $did_height = true;
  247. }
  248. // Calculate the larger/smaller ratios
  249. $smaller_ratio = min( $width_ratio, $height_ratio );
  250. $larger_ratio = max( $width_ratio, $height_ratio );
  251. if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
  252. // The larger ratio is too big. It would result in an overflow.
  253. $ratio = $smaller_ratio;
  254. else
  255. // The larger ratio fits, and is likely to be a more "snug" fit.
  256. $ratio = $larger_ratio;
  257. $w = intval( $current_width * $ratio );
  258. $h = intval( $current_height * $ratio );
  259. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  260. // We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.
  261. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  262. if ( $did_width && $w == $max_width - 1 )
  263. $w = $max_width; // Round it up
  264. if ( $did_height && $h == $max_height - 1 )
  265. $h = $max_height; // Round it up
  266. return array( $w, $h );
  267. }
  268. /**
  269. * Retrieve calculated resized dimensions for use in WP_Image_Editor.
  270. *
  271. * Calculate dimensions and coordinates for a resized image that fits within a
  272. * specified width and height. If $crop is true, the largest matching central
  273. * portion of the image will be cropped out and resized to the required size.
  274. *
  275. * @since 2.5.0
  276. * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and
  277. * $crop to provide custom resize dimensions.
  278. *
  279. * @param int $orig_w Original width.
  280. * @param int $orig_h Original height.
  281. * @param int $dest_w New width.
  282. * @param int $dest_h New height.
  283. * @param bool $crop Optional, default is false. Whether to crop image or resize.
  284. * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function.
  285. */
  286. function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
  287. if ($orig_w <= 0 || $orig_h <= 0)
  288. return false;
  289. // at least one of dest_w or dest_h must be specific
  290. if ($dest_w <= 0 && $dest_h <= 0)
  291. return false;
  292. // plugins can use this to provide custom resize dimensions
  293. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  294. if ( null !== $output )
  295. return $output;
  296. if ( $crop ) {
  297. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  298. $aspect_ratio = $orig_w / $orig_h;
  299. $new_w = min($dest_w, $orig_w);
  300. $new_h = min($dest_h, $orig_h);
  301. if ( !$new_w ) {
  302. $new_w = intval($new_h * $aspect_ratio);
  303. }
  304. if ( !$new_h ) {
  305. $new_h = intval($new_w / $aspect_ratio);
  306. }
  307. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  308. $crop_w = round($new_w / $size_ratio);
  309. $crop_h = round($new_h / $size_ratio);
  310. $s_x = floor( ($orig_w - $crop_w) / 2 );
  311. $s_y = floor( ($orig_h - $crop_h) / 2 );
  312. } else {
  313. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  314. $crop_w = $orig_w;
  315. $crop_h = $orig_h;
  316. $s_x = 0;
  317. $s_y = 0;
  318. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  319. }
  320. // if the resulting image would be the same size or larger we don't want to resize it
  321. if ( $new_w >= $orig_w && $new_h >= $orig_h )
  322. return false;
  323. // the return array matches the parameters to imagecopyresampled()
  324. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  325. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  326. }
  327. /**
  328. * Resize an image to make a thumbnail or intermediate size.
  329. *
  330. * The returned array has the file size, the image width, and image height. The
  331. * filter 'image_make_intermediate_size' can be used to hook in and change the
  332. * values of the returned array. The only parameter is the resized file path.
  333. *
  334. * @since 2.5.0
  335. *
  336. * @param string $file File path.
  337. * @param int $width Image width.
  338. * @param int $height Image height.
  339. * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
  340. * @return bool|array False, if no image was created. Metadata array on success.
  341. */
  342. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  343. if ( $width || $height ) {
  344. $editor = wp_get_image_editor( $file );
  345. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  346. return false;
  347. $resized_file = $editor->save();
  348. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  349. unset( $resized_file['path'] );
  350. return $resized_file;
  351. }
  352. }
  353. return false;
  354. }
  355. /**
  356. * Retrieve the image's intermediate size (resized) path, width, and height.
  357. *
  358. * The $size parameter can be an array with the width and height respectively.
  359. * If the size matches the 'sizes' metadata array for width and height, then it
  360. * will be used. If there is no direct match, then the nearest image size larger
  361. * than the specified size will be used. If nothing is found, then the function
  362. * will break out and return false.
  363. *
  364. * The metadata 'sizes' is used for compatible sizes that can be used for the
  365. * parameter $size value.
  366. *
  367. * The url path will be given, when the $size parameter is a string.
  368. *
  369. * If you are passing an array for the $size, you should consider using
  370. * add_image_size() so that a cropped version is generated. It's much more
  371. * efficient than having to find the closest-sized image and then having the
  372. * browser scale down the image.
  373. *
  374. * @since 2.5.0
  375. * @see add_image_size()
  376. *
  377. * @param int $post_id Attachment ID for image.
  378. * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
  379. * @return bool|array False on failure or array of file path, width, and height on success.
  380. */
  381. function image_get_intermediate_size($post_id, $size='thumbnail') {
  382. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
  383. return false;
  384. // get the best one for a specified set of dimensions
  385. if ( is_array($size) && !empty($imagedata['sizes']) ) {
  386. foreach ( $imagedata['sizes'] as $_size => $data ) {
  387. // already cropped to width or height; so use this size
  388. if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
  389. $file = $data['file'];
  390. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  391. return compact( 'file', 'width', 'height' );
  392. }
  393. // add to lookup table: area => size
  394. $areas[$data['width'] * $data['height']] = $_size;
  395. }
  396. if ( !$size || !empty($areas) ) {
  397. // find for the smallest image not smaller than the desired size
  398. ksort($areas);
  399. foreach ( $areas as $_size ) {
  400. $data = $imagedata['sizes'][$_size];
  401. if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
  402. // Skip images with unexpectedly divergent aspect ratios (crops)
  403. // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
  404. $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
  405. // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size
  406. if ( 'thumbnail' != $_size && ( !$maybe_cropped || ( $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] ) || ( $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'] ) ) )
  407. continue;
  408. // If we're still here, then we're going to use this size
  409. $file = $data['file'];
  410. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  411. return compact( 'file', 'width', 'height' );
  412. }
  413. }
  414. }
  415. }
  416. if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
  417. return false;
  418. $data = $imagedata['sizes'][$size];
  419. // include the full filesystem path of the intermediate file
  420. if ( empty($data['path']) && !empty($data['file']) ) {
  421. $file_url = wp_get_attachment_url($post_id);
  422. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  423. $data['url'] = path_join( dirname($file_url), $data['file'] );
  424. }
  425. return $data;
  426. }
  427. /**
  428. * Get the available image sizes
  429. * @since 3.0.0
  430. * @return array Returns a filtered array of image size strings
  431. */
  432. function get_intermediate_image_sizes() {
  433. global $_wp_additional_image_sizes;
  434. $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
  435. if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
  436. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  437. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  438. }
  439. /**
  440. * Retrieve an image to represent an attachment.
  441. *
  442. * A mime icon for files, thumbnail or intermediate size for images.
  443. *
  444. * @since 2.5.0
  445. *
  446. * @param int $attachment_id Image attachment ID.
  447. * @param string $size Optional, default is 'thumbnail'.
  448. * @param bool $icon Optional, default is false. Whether it is an icon.
  449. * @return bool|array Returns an array (url, width, height), or false, if no image is available.
  450. */
  451. function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
  452. // get a thumbnail or intermediate image if there is one
  453. if ( $image = image_downsize($attachment_id, $size) )
  454. return $image;
  455. $src = false;
  456. if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
  457. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
  458. $src_file = $icon_dir . '/' . wp_basename($src);
  459. @list($width, $height) = getimagesize($src_file);
  460. }
  461. if ( $src && $width && $height )
  462. return array( $src, $width, $height );
  463. return false;
  464. }
  465. /**
  466. * Get an HTML img element representing an image attachment
  467. *
  468. * While $size will accept an array, it is better to register a size with
  469. * add_image_size() so that a cropped version is generated. It's much more
  470. * efficient than having to find the closest-sized image and then having the
  471. * browser scale down the image.
  472. *
  473. * @see add_image_size()
  474. * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array
  475. * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
  476. * @since 2.5.0
  477. *
  478. * @param int $attachment_id Image attachment ID.
  479. * @param string $size Optional, default is 'thumbnail'.
  480. * @param bool $icon Optional, default is false. Whether it is an icon.
  481. * @param mixed $attr Optional, attributes for the image markup.
  482. * @return string HTML img element or empty string on failure.
  483. */
  484. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  485. $html = '';
  486. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  487. if ( $image ) {
  488. list($src, $width, $height) = $image;
  489. $hwstring = image_hwstring($width, $height);
  490. if ( is_array($size) )
  491. $size = join('x', $size);
  492. $attachment = get_post($attachment_id);
  493. $default_attr = array(
  494. 'src' => $src,
  495. 'class' => "attachment-$size",
  496. 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
  497. );
  498. if ( empty($default_attr['alt']) )
  499. $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
  500. if ( empty($default_attr['alt']) )
  501. $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
  502. $attr = wp_parse_args($attr, $default_attr);
  503. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
  504. $attr = array_map( 'esc_attr', $attr );
  505. $html = rtrim("<img $hwstring");
  506. foreach ( $attr as $name => $value ) {
  507. $html .= " $name=" . '"' . $value . '"';
  508. }
  509. $html .= ' />';
  510. }
  511. return $html;
  512. }
  513. /**
  514. * Adds a 'wp-post-image' class to post thumbnails
  515. * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
  516. * dynamically add/remove itself so as to only filter post thumbnails
  517. *
  518. * @since 2.9.0
  519. * @param array $attr Attributes including src, class, alt, title
  520. * @return array
  521. */
  522. function _wp_post_thumbnail_class_filter( $attr ) {
  523. $attr['class'] .= ' wp-post-image';
  524. return $attr;
  525. }
  526. /**
  527. * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
  528. *
  529. * @since 2.9.0
  530. */
  531. function _wp_post_thumbnail_class_filter_add( $attr ) {
  532. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  533. }
  534. /**
  535. * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
  536. *
  537. * @since 2.9.0
  538. */
  539. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  540. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  541. }
  542. add_shortcode('wp_caption', 'img_caption_shortcode');
  543. add_shortcode('caption', 'img_caption_shortcode');
  544. /**
  545. * The Caption shortcode.
  546. *
  547. * Allows a plugin to replace the content that would otherwise be returned. The
  548. * filter is 'img_caption_shortcode' and passes an empty string, the attr
  549. * parameter and the content parameter values.
  550. *
  551. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  552. * 'caption'.
  553. *
  554. * @since 2.6.0
  555. *
  556. * @param array $attr Attributes attributed to the shortcode.
  557. * @param string $content Optional. Shortcode content.
  558. * @return string
  559. */
  560. function img_caption_shortcode($attr, $content = null) {
  561. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  562. if ( ! isset( $attr['caption'] ) ) {
  563. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  564. $content = $matches[1];
  565. $attr['caption'] = trim( $matches[2] );
  566. }
  567. }
  568. // Allow plugins/themes to override the default caption template.
  569. $output = apply_filters('img_caption_shortcode', '', $attr, $content);
  570. if ( $output != '' )
  571. return $output;
  572. extract(shortcode_atts(array(
  573. 'id' => '',
  574. 'align' => 'alignnone',
  575. 'width' => '',
  576. 'caption' => ''
  577. ), $attr, 'caption'));
  578. if ( 1 > (int) $width || empty($caption) )
  579. return $content;
  580. if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
  581. return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
  582. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
  583. }
  584. add_shortcode('gallery', 'gallery_shortcode');
  585. /**
  586. * The Gallery shortcode.
  587. *
  588. * This implements the functionality of the Gallery Shortcode for displaying
  589. * WordPress images on a post.
  590. *
  591. * @since 2.5.0
  592. *
  593. * @param array $attr Attributes of the shortcode.
  594. * @return string HTML content to display gallery.
  595. */
  596. function gallery_shortcode($attr) {
  597. $post = get_post();
  598. static $instance = 0;
  599. $instance++;
  600. if ( ! empty( $attr['ids'] ) ) {
  601. // 'ids' is explicitly ordered, unless you specify otherwise.
  602. if ( empty( $attr['orderby'] ) )
  603. $attr['orderby'] = 'post__in';
  604. $attr['include'] = $attr['ids'];
  605. }
  606. // Allow plugins/themes to override the default gallery template.
  607. $output = apply_filters('post_gallery', '', $attr);
  608. if ( $output != '' )
  609. return $output;
  610. // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
  611. if ( isset( $attr['orderby'] ) ) {
  612. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  613. if ( !$attr['orderby'] )
  614. unset( $attr['orderby'] );
  615. }
  616. extract(shortcode_atts(array(
  617. 'order' => 'ASC',
  618. 'orderby' => 'menu_order ID',
  619. 'id' => $post ? $post->ID : 0,
  620. 'itemtag' => 'dl',
  621. 'icontag' => 'dt',
  622. 'captiontag' => 'dd',
  623. 'columns' => 3,
  624. 'size' => 'thumbnail',
  625. 'include' => '',
  626. 'exclude' => ''
  627. ), $attr, 'gallery'));
  628. $id = intval($id);
  629. if ( 'RAND' == $order )
  630. $orderby = 'none';
  631. if ( !empty($include) ) {
  632. $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  633. $attachments = array();
  634. foreach ( $_attachments as $key => $val ) {
  635. $attachments[$val->ID] = $_attachments[$key];
  636. }
  637. } elseif ( !empty($exclude) ) {
  638. $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  639. } else {
  640. $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  641. }
  642. if ( empty($attachments) )
  643. return '';
  644. if ( is_feed() ) {
  645. $output = "\n";
  646. foreach ( $attachments as $att_id => $attachment )
  647. $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  648. return $output;
  649. }
  650. $itemtag = tag_escape($itemtag);
  651. $captiontag = tag_escape($captiontag);
  652. $icontag = tag_escape($icontag);
  653. $valid_tags = wp_kses_allowed_html( 'post' );
  654. if ( ! isset( $valid_tags[ $itemtag ] ) )
  655. $itemtag = 'dl';
  656. if ( ! isset( $valid_tags[ $captiontag ] ) )
  657. $captiontag = 'dd';
  658. if ( ! isset( $valid_tags[ $icontag ] ) )
  659. $icontag = 'dt';
  660. $columns = intval($columns);
  661. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  662. $float = is_rtl() ? 'right' : 'left';
  663. $selector = "gallery-{$instance}";
  664. $gallery_style = $gallery_div = '';
  665. if ( apply_filters( 'use_default_gallery_style', true ) )
  666. $gallery_style = "
  667. <style type='text/css'>
  668. #{$selector} {
  669. margin: auto;
  670. }
  671. #{$selector} .gallery-item {
  672. float: {$float};
  673. margin-top: 10px;
  674. text-align: center;
  675. width: {$itemwidth}%;
  676. }
  677. #{$selector} img {
  678. border: 2px solid #cfcfcf;
  679. }
  680. #{$selector} .gallery-caption {
  681. margin-left: 0;
  682. }
  683. /* see gallery_shortcode() in wp-includes/media.php */
  684. </style>";
  685. $size_class = sanitize_html_class( $size );
  686. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  687. $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );
  688. $i = 0;
  689. foreach ( $attachments as $id => $attachment ) {
  690. $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false);
  691. $image_meta = wp_get_attachment_metadata( $id );
  692. $orientation = '';
  693. if ( isset( $image_meta['height'], $image_meta['width'] ) )
  694. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  695. $output .= "<{$itemtag} class='gallery-item'>";
  696. $output .= "
  697. <{$icontag} class='gallery-icon {$orientation}'>
  698. $link
  699. </{$icontag}>";
  700. if ( $captiontag && trim($attachment->post_excerpt) ) {
  701. $output .= "
  702. <{$captiontag} class='wp-caption-text gallery-caption'>
  703. " . wptexturize($attachment->post_excerpt) . "
  704. </{$captiontag}>";
  705. }
  706. $output .= "</{$itemtag}>";
  707. if ( $columns > 0 && ++$i % $columns == 0 )
  708. $output .= '<br style="clear: both" />';
  709. }
  710. $output .= "
  711. <br style='clear: both;' />
  712. </div>\n";
  713. return $output;
  714. }
  715. /**
  716. * Provide a No-JS Flash fallback as a last resort for audio / video
  717. *
  718. * @since 3.6.0
  719. *
  720. * @param string $url
  721. * @return string Fallback HTML
  722. */
  723. function wp_mediaelement_fallback( $url ) {
  724. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  725. }
  726. /**
  727. * Return a filtered list of WP-supported audio formats
  728. *
  729. * @since 3.6.0
  730. * @return array
  731. */
  732. function wp_get_audio_extensions() {
  733. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
  734. }
  735. /**
  736. * The Audio shortcode.
  737. *
  738. * This implements the functionality of the Audio Shortcode for displaying
  739. * WordPress mp3s in a post.
  740. *
  741. * @since 3.6.0
  742. *
  743. * @param array $attr Attributes of the shortcode.
  744. * @return string HTML content to display audio.
  745. */
  746. function wp_audio_shortcode( $attr ) {
  747. $post_id = get_post() ? get_the_ID() : 0;
  748. static $instances = 0;
  749. $instances++;
  750. $audio = null;
  751. $default_types = wp_get_audio_extensions();
  752. $defaults_atts = array( 'src' => '' );
  753. foreach ( $default_types as $type )
  754. $defaults_atts[$type] = '';
  755. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  756. extract( $atts );
  757. $primary = false;
  758. if ( ! empty( $src ) ) {
  759. $type = wp_check_filetype( $src );
  760. if ( ! in_array( $type['ext'], $default_types ) )
  761. return sprintf( '<a class="wp-post-format-link-audio" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  762. $primary = true;
  763. array_unshift( $default_types, 'src' );
  764. } else {
  765. foreach ( $default_types as $ext ) {
  766. if ( ! empty( $$ext ) ) {
  767. $type = wp_check_filetype( $$ext );
  768. if ( $type['ext'] === $ext )
  769. $primary = true;
  770. }
  771. }
  772. }
  773. if ( ! $primary ) {
  774. $audios = get_attached_audio( $post_id );
  775. if ( empty( $audios ) )
  776. return;
  777. $audio = reset( $audios );
  778. $src = wp_get_attachment_url( $audio->ID );
  779. if ( empty( $src ) )
  780. return;
  781. array_unshift( $default_types, 'src' );
  782. }
  783. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  784. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  785. wp_enqueue_style( 'wp-mediaelement' );
  786. wp_enqueue_script( 'wp-mediaelement' );
  787. }
  788. $atts = array(
  789. sprintf( 'class="%s"', apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ) ),
  790. sprintf( 'id="audio-%d-%d"', $post_id, $instances ),
  791. );
  792. $html = sprintf( '<audio %s controls="controls" preload="none">', join( ' ', $atts ) );
  793. $fileurl = '';
  794. $source = '<source type="%s" src="%s" />';
  795. foreach ( $default_types as $fallback ) {
  796. if ( ! empty( $$fallback ) ) {
  797. if ( empty( $fileurl ) )
  798. $fileurl = $$fallback;
  799. $type = wp_check_filetype( $$fallback );
  800. $html .= sprintf( $source, $type['type'], esc_url( $$fallback ) );
  801. }
  802. }
  803. if ( 'mediaelement' === $library )
  804. $html .= wp_mediaelement_fallback( $fileurl );
  805. $html .= '</audio>';
  806. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id );
  807. }
  808. add_shortcode( 'audio', apply_filters( 'wp_audio_shortcode_handler', 'wp_audio_shortcode' ) );
  809. /**
  810. * Return a filtered list of WP-supported video formats
  811. *
  812. * @since 3.6.0
  813. * @return array
  814. */
  815. function wp_get_video_extensions() {
  816. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  817. }
  818. /**
  819. * The Video shortcode.
  820. *
  821. * This implements the functionality of the Video Shortcode for displaying
  822. * WordPress mp4s in a post.
  823. *
  824. * @since 3.6.0
  825. *
  826. * @param array $attr Attributes of the shortcode.
  827. * @return string HTML content to display video.
  828. */
  829. function wp_video_shortcode( $attr ) {
  830. global $content_width;
  831. $post_id = get_post() ? get_the_ID() : 0;
  832. static $instances = 0;
  833. $instances++;
  834. $video = null;
  835. $default_types = wp_get_video_extensions();
  836. $defaults_atts = array(
  837. 'src' => '',
  838. 'poster' => '',
  839. 'height' => 360,
  840. 'width' => empty( $content_width ) ? 640 : $content_width,
  841. );
  842. foreach ( $default_types as $type )
  843. $defaults_atts[$type] = '';
  844. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  845. extract( $atts );
  846. $w = $width;
  847. $h = $height;
  848. if ( is_admin() && $width > 600 )
  849. $w = 600;
  850. elseif ( ! is_admin() && $w > $defaults_atts['width'] )
  851. $w = $defaults_atts['width'];
  852. if ( $w < $width )
  853. $height = round( ( $h * $w ) / $width );
  854. $width = $w;
  855. $primary = false;
  856. if ( ! empty( $src ) ) {
  857. $type = wp_check_filetype( $src );
  858. if ( ! in_array( $type['ext'], $default_types ) )
  859. return sprintf( '<a class="wp-post-format-link-video" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  860. $primary = true;
  861. array_unshift( $default_types, 'src' );
  862. } else {
  863. foreach ( $default_types as $ext ) {
  864. if ( ! empty( $$ext ) ) {
  865. $type = wp_check_filetype( $$ext );
  866. if ( $type['ext'] === $ext )
  867. $primary = true;
  868. }
  869. }
  870. }
  871. if ( ! $primary ) {
  872. $videos = get_attached_video( $post_id );
  873. if ( empty( $videos ) )
  874. return;
  875. $video = reset( $videos );
  876. $src = wp_get_attachment_url( $video->ID );
  877. if ( empty( $src ) )
  878. return;
  879. array_unshift( $default_types, 'src' );
  880. }
  881. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  882. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  883. wp_enqueue_style( 'wp-mediaelement' );
  884. wp_enqueue_script( 'wp-mediaelement' );
  885. }
  886. $atts = array(
  887. sprintf( 'class="%s"', apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ) ),
  888. sprintf( 'id="video-%d-%d"', $post_id, $instances ),
  889. sprintf( 'width="%d"', $width ),
  890. sprintf( 'height="%d"', $height ),
  891. );
  892. if ( ! empty( $poster ) )
  893. $atts[] = sprintf( 'poster="%s"', esc_url( $poster ) );
  894. $html = sprintf( '<video %s controls="controls" preload="none">', join( ' ', $atts ) );
  895. $fileurl = '';
  896. $source = '<source type="%s" src="%s" />';
  897. foreach ( $default_types as $fallback ) {
  898. if ( ! empty( $$fallback ) ) {
  899. if ( empty( $fileurl ) )
  900. $fileurl = $$fallback;
  901. $type = wp_check_filetype( $$fallback );
  902. // m4v sometimes shows up as video/mpeg which collides with mp4
  903. if ( 'm4v' === $type['ext'] )
  904. $type['type'] = 'video/m4v';
  905. $html .= sprintf( $source, $type['type'], esc_url( $$fallback ) );
  906. }
  907. }
  908. if ( 'mediaelement' === $library )
  909. $html .= wp_mediaelement_fallback( $fileurl );
  910. $html .= '</video>';
  911. return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id );
  912. }
  913. add_shortcode( 'video', apply_filters( 'wp_video_shortcode_handler', 'wp_video_shortcode' ) );
  914. /**
  915. * Display previous image link that has the same post parent.
  916. *
  917. * @since 2.5.0
  918. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  919. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  920. * @return string HTML content.
  921. */
  922. function previous_image_link($size = 'thumbnail', $text = false) {
  923. adjacent_image_link(true, $size, $text);
  924. }
  925. /**
  926. * Display next image link that has the same post parent.
  927. *
  928. * @since 2.5.0
  929. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  930. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  931. * @return string HTML content.
  932. */
  933. function next_image_link($size = 'thumbnail', $text = false) {
  934. adjacent_image_link(false, $size, $text);
  935. }
  936. /**
  937. * Display next or previous image link that has the same post parent.
  938. *
  939. * Retrieves the current attachment object from the $post global.
  940. *
  941. * @since 2.5.0
  942. *
  943. * @param bool $prev Optional. Default is true to display previous link, false for next.
  944. */
  945. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  946. $post = get_post();
  947. $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
  948. foreach ( $attachments as $k => $attachment )
  949. if ( $attachment->ID == $post->ID )
  950. break;
  951. $k = $prev ? $k - 1 : $k + 1;
  952. $output = $attachment_id = null;
  953. if ( isset( $attachments[ $k ] ) ) {
  954. $attachment_id = $attachments[ $k ]->ID;
  955. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  956. }
  957. $adjacent = $prev ? 'previous' : 'next';
  958. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  959. }
  960. /**
  961. * Retrieve taxonomies attached to the attachment.
  962. *
  963. * @since 2.5.0
  964. *
  965. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  966. * @return array Empty array on failure. List of taxonomies on success.
  967. */
  968. function get_attachment_taxonomies($attachment) {
  969. if ( is_int( $attachment ) )
  970. $attachment = get_post($attachment);
  971. else if ( is_array($attachment) )
  972. $attachment = (object) $attachment;
  973. if ( ! is_object($attachment) )
  974. return array();
  975. $filename = basename($attachment->guid);
  976. $objects = array('attachment');
  977. if ( false !== strpos($filename, '.') )
  978. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  979. if ( !empty($attachment->post_mime_type) ) {
  980. $objects[] = 'attachment:' . $attachment->post_mime_type;
  981. if ( false !== strpos($attachment->post_mime_type, '/') )
  982. foreach ( explode('/', $attachment->post_mime_type) as $token )
  983. if ( !empty($token) )
  984. $objects[] = "attachment:$token";
  985. }
  986. $taxonomies = array();
  987. foreach ( $objects as $object )
  988. if ( $taxes = get_object_taxonomies($object) )
  989. $taxonomies = array_merge($taxonomies, $taxes);
  990. return array_unique($taxonomies);
  991. }
  992. /**
  993. * Return all of the taxonomy names that are registered for attachments.
  994. *
  995. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  996. *
  997. * @since 3.5.0
  998. * @see get_attachment_taxonomies()
  999. * @uses get_taxonomies()
  1000. *
  1001. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  1002. * @return array The names of all taxonomy of $object_type.
  1003. */
  1004. function get_taxonomies_for_attachments( $output = 'names' ) {
  1005. $taxonomies = array();
  1006. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1007. foreach ( $taxonomy->object_type as $object_type ) {
  1008. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  1009. if ( 'names' == $output )
  1010. $taxonomies[] = $taxonomy->name;
  1011. else
  1012. $taxonomies[ $taxonomy->name ] = $taxonomy;
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. return $taxonomies;
  1018. }
  1019. /**
  1020. * Create new GD image resource with transparency support
  1021. * @TODO: Deprecate if possible.
  1022. *
  1023. * @since 2.9.0
  1024. *
  1025. * @param int $width Image width
  1026. * @param int $height Image height
  1027. * @return image resource
  1028. */
  1029. function wp_imagecreatetruecolor($width, $height) {
  1030. $img = imagecreatetruecolor($width, $height);
  1031. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1032. imagealphablending($img, false);
  1033. imagesavealpha($img, true);
  1034. }
  1035. return $img;
  1036. }
  1037. /**
  1038. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1039. *
  1040. * @since 2.9.0
  1041. * @see WP_Embed::register_handler()
  1042. */
  1043. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1044. global $wp_embed;
  1045. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  1046. }
  1047. /**
  1048. * Unregister a previously registered embed handler.
  1049. *
  1050. * @since 2.9.0
  1051. * @see WP_Embed::unregister_handler()
  1052. */
  1053. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1054. global $wp_embed;
  1055. $wp_embed->unregister_handler( $id, $priority );
  1056. }
  1057. /**
  1058. * Create default array of embed parameters.
  1059. *
  1060. * The width defaults to the content width as specified by the theme. If the
  1061. * theme does not specify a content width, then 500px is used.
  1062. *
  1063. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  1064. *
  1065. * The 'embed_defaults' filter can be used to adjust either of these values.
  1066. *
  1067. * @since 2.9.0
  1068. *
  1069. * @return array Default embed parameters.
  1070. */
  1071. function wp_embed_defaults() {
  1072. if ( ! empty( $GLOBALS['content_width'] ) )
  1073. $width = (int) $GLOBALS['content_width'];
  1074. if ( empty( $width ) )
  1075. $width = 500;
  1076. $height = min( ceil( $width * 1.5 ), 1000 );
  1077. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  1078. }
  1079. /**
  1080. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1081. *
  1082. * @since 2.9.0
  1083. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  1084. *
  1085. * @param int $example_width The width of an example embed.
  1086. * @param int $example_height The height of an example embed.
  1087. * @param int $max_width The maximum allowed width.
  1088. * @param int $max_height The maximum allowed height.
  1089. * @return array The maximum possible width and height based on the example ratio.
  1090. */
  1091. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1092. $example_width = (int) $example_width;
  1093. $example_height = (int) $example_height;
  1094. $max_width = (int) $max_width;
  1095. $max_height = (int) $max_height;
  1096. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  1097. }
  1098. /**
  1099. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1100. *
  1101. * @since 2.9.0
  1102. * @see WP_oEmbed
  1103. *
  1104. * @uses _wp_oembed_get_object()
  1105. * @uses WP_oEmbed::get_html()
  1106. *
  1107. * @param string $url The URL that should be embedded.
  1108. * @param array $args Additional arguments and parameters.
  1109. * @return bool|string False on failure or the embed HTML on success.
  1110. */
  1111. function wp_oembed_get( $url, $args = '' ) {
  1112. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1113. $oembed = _wp_oembed_get_object();
  1114. return $oembed->get_html( $url, $args );
  1115. }
  1116. /**
  1117. * Adds a URL format and oEmbed provider URL pair.
  1118. *
  1119. * @since 2.9.0
  1120. * @see WP_oEmbed
  1121. *
  1122. * @uses _wp_oembed_get_object()
  1123. *
  1124. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1125. * @param string $provider The URL to the oEmbed provider.
  1126. * @param boolean $regex Whether the $format parameter is in a regex format.
  1127. */
  1128. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1129. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1130. $oembed = _wp_oembed_get_object();
  1131. $oembed->providers[$format] = array( $provider, $regex );
  1132. }
  1133. /**
  1134. * Removes an oEmbed provider.
  1135. *
  1136. * @since 3.5.0
  1137. * @see WP_oEmbed
  1138. *
  1139. * @uses _wp_oembed_get_object()
  1140. *
  1141. * @param string $format The URL format for the oEmbed provider to remove.
  1142. */
  1143. function wp_oembed_remove_provider( $format ) {
  1144. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1145. $oembed = _wp_oembed_get_object();
  1146. if ( isset( $oembed->providers[ $format ] ) ) {
  1147. unset( $oembed->providers[ $format ] );
  1148. return true;
  1149. }
  1150. return false;
  1151. }
  1152. /**
  1153. * Determines if default embed handlers should be loaded.
  1154. *
  1155. * Checks to make sure that the embeds library hasn't already been loaded. If
  1156. * it hasn't, then it will load the embeds library.
  1157. *
  1158. * @since 2.9.0
  1159. */
  1160. function wp_maybe_load_embeds() {
  1161. if ( ! apply_filters( 'load_default_embeds', true ) )
  1162. return;
  1163. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  1164. wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
  1165. wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  1166. }
  1167. /**
  1168. * The Google Video embed handler callback. Google Video does not support oEmbed.
  1169. *
  1170. * @see WP_Embed::register_handler()
  1171. * @see WP_Embed::shortcode()
  1172. *
  1173. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1174. * @param array $attr Embed attributes.
  1175. * @param string $url The original URL that was matched by the regex.
  1176. * @param array $rawattr The original unmodified attributes.
  1177. * @return string The embed HTML.
  1178. */
  1179. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1180. // If the user supplied a fixed width AND height, use it
  1181. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1182. $width = (int) $rawattr['width'];
  1183. $height = (int) $rawattr['height'];
  1184. } else {
  1185. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1186. }
  1187. return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&amp;hl=en&amp;fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr );
  1188. }
  1189. /**
  1190. * Audio embed handler callback.
  1191. *
  1192. * @since 3.6.0
  1193. *
  1194. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1195. * @param array $attr Embed attributes.
  1196. * @param string $url The original URL that was matched by the regex.
  1197. * @param array $rawattr The original unmodified attributes.
  1198. * @return string The embed HTML.
  1199. */
  1200. function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  1201. $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
  1202. return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  1203. }
  1204. /**
  1205. * Video embed handler callback.
  1206. *
  1207. * @since 3.6.0
  1208. *
  1209. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1210. * @param array $attr Embed attributes.
  1211. * @param string $url The original URL that was matched by the regex.
  1212. * @param array $rawattr The original unmodified attributes.
  1213. * @return string The embed HTML.
  1214. */
  1215. function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  1216. $dimensions = '';
  1217. if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  1218. $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  1219. $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  1220. } elseif ( strstr( $url, home_url() ) ) {
  1221. $id = attachment_url_to_postid( $url );
  1222. if ( ! empty( $id ) ) {
  1223. $meta = wp_get_attachment_metadata( $id );
  1224. if ( ! empty( $meta['width'] ) )
  1225. $dimensions .= sprintf( 'width="%d" ', (int) $meta['width'] );
  1226. if ( ! empty( $meta['height'] ) )
  1227. $dimensions .= sprintf( 'height="%d" ', (int) $meta['height'] );
  1228. }
  1229. }
  1230. $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
  1231. return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  1232. }
  1233. /**
  1234. * Converts a shorthand byte value to an integer byte value.
  1235. *
  1236. * @since 2.3.0
  1237. *
  1238. * @param string $size A shorthand byte value.
  1239. * @return int An integer byte value.
  1240. */
  1241. function wp_convert_hr_to_bytes( $size ) {
  1242. $size = strtolower( $size );
  1243. $bytes = (int) $size;
  1244. if ( strpos( $size, 'k' ) !== false )
  1245. $bytes = intval( $size ) * 1024;
  1246. elseif ( strpos( $size, 'm' ) !== false )
  1247. $bytes = intval($size) * 1024 * 1024;
  1248. elseif ( strpos( $size, 'g' ) !== false )
  1249. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  1250. return $bytes;
  1251. }
  1252. /**
  1253. * Determine the maximum upload size allowed in php.ini.
  1254. *
  1255. * @since 2.5.0
  1256. *
  1257. * @return int Allowed upload size.
  1258. */
  1259. function wp_max_upload_size() {
  1260. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  1261. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  1262. $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  1263. return $bytes;
  1264. }
  1265. /**
  1266. * Returns a WP_Image_Editor instance and loads file into it.
  1267. *
  1268. * @since 3.5.0
  1269. * @access public
  1270. *
  1271. * @param string $path Path to file to load
  1272. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1273. * @return WP_Image_Editor|WP_Error
  1274. */
  1275. function wp_get_image_editor( $path, $args = array() ) {
  1276. $args['path'] = $path;
  1277. if ( ! isset( $args['mime_type'] ) ) {
  1278. $file_info = wp_check_filetype( $args['path'] );
  1279. // If $file_info['type'] is false, then we let the editor attempt to
  1280. // figure out the file type, rather than forcing a failure based on extension.
  1281. if ( isset( $file_info ) && $file_info['type'] )
  1282. $args['mime_type'] = $file_info['type'];
  1283. }
  1284. $implementation = _wp_image_editor_choose( $args );
  1285. if ( $implementation ) {
  1286. $editor = new $implementation( $path );
  1287. $loaded = $editor->load();
  1288. if ( is_wp_error( $loaded ) )
  1289. return $loaded;
  1290. return $editor;
  1291. }
  1292. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  1293. }
  1294. /**
  1295. * Tests whether there is an editor that supports a given mime type or methods.
  1296. *
  1297. * @since 3.5.0
  1298. * @access public
  1299. *
  1300. * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1301. * @return boolean true if an eligible editor is found; false otherwise
  1302. */
  1303. function wp_image_editor_supports( $args = array() ) {
  1304. return (bool) _wp_image_editor_choose( $args );
  1305. }
  1306. /**
  1307. * Tests which editors are capable of supporting the request.
  1308. *
  1309. * @since 3.5.0
  1310. * @access private
  1311. *
  1312. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  1313. * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  1314. */
  1315. function _wp_image_editor_choose( $args = array() ) {
  1316. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  1317. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  1318. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  1319. $implementations = apply_filters( 'wp_image_editors',
  1320. array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  1321. foreach ( $implementations as $implementation ) {
  1322. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  1323. continue;
  1324. if ( isset( $args['mime_type'] ) &&
  1325. ! call_user_func(
  1326. array( $implementation, 'supports_mime_type' ),
  1327. $args['mime_type'] ) ) {
  1328. continue;
  1329. }
  1330. if ( isset( $args['methods'] ) &&
  1331. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  1332. continue;
  1333. }
  1334. return $implementation;
  1335. }
  1336. return false;
  1337. }
  1338. /**
  1339. * Prints default plupload arguments.
  1340. *
  1341. * @since 3.4.0
  1342. */
  1343. function wp_plupload_default_settings() {
  1344. global $wp_scripts;
  1345. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  1346. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  1347. return;
  1348. $max_upload_size = wp_max_upload_size();
  1349. $defaults = array(
  1350. 'runtimes' => 'html5,silverlight,flash,html4',
  1351. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  1352. 'multiple_queues' => true,
  1353. 'max_file_size' => $max_upload_size . 'b',
  1354. 'url' => admin_url( 'async-upload.php', 'relative' ),
  1355. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  1356. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  1357. 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ),
  1358. 'multipart' => true,
  1359. 'urlstream_upload' => true,
  1360. );
  1361. // Multi-file uploading doesn't currently work in iOS Safari,
  1362. // single-file allows the built-in camera to be used as source for images
  1363. if ( wp_is_mobile() )
  1364. $defaults['multi_selection'] = false;
  1365. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  1366. $params = array(
  1367. 'action' => 'upload-attachment',
  1368. );
  1369. $params = apply_filters( 'plupload_default_params', $params );
  1370. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  1371. $defaults['multipart_params'] = $params;
  1372. $settings = array(
  1373. 'defaults' => $defaults,
  1374. 'browser' => array(
  1375. 'mobile' => wp_is_mobile(),
  1376. 'supported' => _device_can_upload(),
  1377. ),
  1378. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  1379. );
  1380. $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  1381. if ( $data )
  1382. $script = "$data\n$script";
  1383. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  1384. }
  1385. add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  1386. /**
  1387. * Prepares an attachment post object for JS, where it is expected
  1388. * to be JSON-encoded and fit into an Attachment model.
  1389. *
  1390. * @since 3.5.0
  1391. *
  1392. * @param mixed $attachment Attachment ID or object.
  1393. * @return array Array of attachment details.
  1394. */
  1395. function wp_prepare_attachment_for_js( $attachment ) {
  1396. if ( ! $attachment = get_post( $attachment ) )
  1397. return;
  1398. if ( 'attachment' != $attachment->post_type )
  1399. return;
  1400. $meta = wp_get_attachment_metadata( $attachment->ID );
  1401. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  1402. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  1403. else
  1404. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  1405. $attachment_url = wp_get_attachment_url( $attachment->ID );
  1406. $response = array(
  1407. 'id' => $attachment->ID,
  1408. 'title' => $attachment->post_title,
  1409. 'filename' => basename( $attachment->guid ),
  1410. 'url' => $attachment_url,
  1411. 'link' => get_attachment_link( $attachment->ID ),
  1412. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  1413. 'author' => $attachment->post_author,
  1414. 'description' => $attachment->post_content,
  1415. 'caption' => $attachment->post_excerpt,
  1416. 'name' => $attachment->post_name,
  1417. 'status' => $attachment->post_status,
  1418. 'uploadedTo' => $attachment->post_parent,
  1419. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  1420. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  1421. 'menuOrder' => $attachment->menu_order,
  1422. 'mime' => $attachment->post_mime_type,
  1423. 'type' => $type,
  1424. 'subtype' => $subtype,
  1425. 'icon' => wp_mime_type_icon( $attachment->ID ),
  1426. 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  1427. 'nonces' => array(
  1428. 'update' => false,
  1429. 'delete' => false,
  1430. ),
  1431. 'editLink' => false,
  1432. );
  1433. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  1434. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  1435. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  1436. }
  1437. if ( current_user_can( 'delete_post', $attachment->ID ) )
  1438. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  1439. if ( $meta && 'image' === $type ) {
  1440. $sizes = array();
  1441. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  1442. 'thumbnail' => __('Thumbnail'),
  1443. 'medium' => __('Medium'),
  1444. 'large' => __('Large'),
  1445. 'full' => __('Full Size'),
  1446. ) );
  1447. unset( $possible_sizes['full'] );
  1448. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  1449. // First: run the image_downsize filter. If it returns something, we can use its data.
  1450. // If the filter does not return something, then image_downsize() is just an expensive
  1451. // way to check the image metadata, which we do second.
  1452. foreach ( $possible_sizes as $size => $label ) {
  1453. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  1454. if ( ! $downsize[3] )
  1455. continue;
  1456. $sizes[ $size ] = array(
  1457. 'height' => $downsize[2],
  1458. 'width' => $downsize[1],
  1459. 'url' => $downsize[0],
  1460. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  1461. );
  1462. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  1463. if ( ! isset( $base_url ) )
  1464. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  1465. // Nothing from the filter, so consult image metadata if we have it.
  1466. $size_meta = $meta['sizes'][ $size ];
  1467. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  1468. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  1469. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  1470. $sizes[ $size ] = array(
  1471. 'height' => $height,
  1472. 'width' => $width,
  1473. 'url' => $base_url . $size_meta['file'],
  1474. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  1475. );
  1476. }
  1477. }
  1478. $sizes['full'] = array( 'url' => $attachment_url );
  1479. if ( isset( $meta['height'], $meta['width'] ) ) {
  1480. $sizes['full']['height'] = $meta['height'];
  1481. $sizes['full']['width'] = $meta['width'];
  1482. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  1483. }
  1484. $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
  1485. } elseif ( $meta && 'video' === $type ) {
  1486. if ( isset( $meta['width'] ) )
  1487. $response['width'] = (int) $meta['width'];
  1488. if ( isset( $meta['height'] ) )
  1489. $response['height'] = (int) $meta['height'];
  1490. }
  1491. if ( function_exists('get_compat_media_markup') )
  1492. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  1493. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  1494. }
  1495. /**
  1496. * Enqueues all scripts, styles, settings, and templates necessary to use
  1497. * all media JS APIs.
  1498. *
  1499. * @since 3.5.0
  1500. */
  1501. function wp_enqueue_media( $args = array() ) {
  1502. // Enqueue me just once per page, please.
  1503. if ( did_action( 'wp_enqueue_media' ) )
  1504. return;
  1505. $defaults = array(
  1506. 'post' => null,
  1507. );
  1508. $args = wp_parse_args( $args, $defaults );
  1509. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  1510. // to ensure plugins will work. We will then unset those tabs.
  1511. $tabs = array(
  1512. // handler action suffix => tab label
  1513. 'type' => '',
  1514. 'type_url' => '',
  1515. 'gallery' => '',
  1516. 'library' => '',
  1517. );
  1518. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  1519. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  1520. $props = array(
  1521. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  1522. 'align' => get_option( 'image_default_align' ), // empty default
  1523. 'size' => get_option( 'image_default_size' ), // empty default
  1524. );
  1525. $settings = array(
  1526. 'tabs' => $tabs,
  1527. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  1528. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  1529. 'captions' => ! apply_filters( 'disable_captions', '' ),
  1530. 'nonce' => array(
  1531. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  1532. ),
  1533. 'post' => array(
  1534. 'id' => 0,
  1535. ),
  1536. 'defaultProps' => $props,
  1537. );
  1538. $post = null;
  1539. if ( isset( $args['post'] ) ) {
  1540. $post = get_post( $args['post'] );
  1541. $settings['post'] = array(
  1542. 'id' => $post->ID,
  1543. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  1544. );
  1545. if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) {
  1546. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  1547. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  1548. }
  1549. }
  1550. $hier = $post && is_post_type_hierarchical( $post->post_type );
  1551. $strings = array(
  1552. // Generic
  1553. 'url' => __( 'URL' ),
  1554. 'addMedia' => __( 'Add Media' ),
  1555. 'search' => __( 'Search' ),
  1556. 'select' => __( 'Select' ),
  1557. 'cancel' => __( 'Cancel' ),
  1558. /* translators: This is a would-be plural string used in the media manager.
  1559. If there is not a word you can use in your language to avoid issues with the
  1560. lack of plural support here, turn it into "selected: %d" then translate it.
  1561. */
  1562. 'selected' => __( '%d selected' ),
  1563. 'dragInfo' => __( 'Drag and drop to reorder images.' ),
  1564. // Upload
  1565. 'uploadFilesTitle' => __( 'Upload Files' ),
  1566. 'uploadImagesTitle' => __( 'Upload Images' ),
  1567. // Library
  1568. 'mediaLibraryTitle' => __( 'Media Library' ),
  1569. 'insertMediaTitle' => __( 'Insert Media' ),
  1570. 'createNewGallery' => __( 'Create a new gallery' ),
  1571. 'returnToLibrary' => __( '&#8592; Return to library' ),
  1572. 'allMediaItems' => __( 'All media items' ),
  1573. 'noItemsFound' => __( 'No items found.' ),
  1574. 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
  1575. 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
  1576. 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
  1577. // From URL
  1578. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  1579. // Featured Images
  1580. 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
  1581. 'setFeaturedImage' => __( 'Set featured image' ),
  1582. // Gallery
  1583. 'createGalleryTitle' => __( 'Create Gallery' ),
  1584. 'editGalleryTitle' => __( 'Edit Gallery' ),
  1585. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  1586. 'insertGallery' => __( 'Insert gallery' ),
  1587. 'updateGallery' => __( 'Update gallery' ),
  1588. 'addToGallery' => __( 'Add to gallery' ),
  1589. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  1590. 'reverseOrder' => __( 'Reverse order' ),
  1591. );
  1592. $settings = apply_filters( 'media_view_settings', $settings, $post );
  1593. $strings = apply_filters( 'media_view_strings', $strings, $post );
  1594. $strings['settings'] = $settings;
  1595. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  1596. wp_enqueue_script( 'media-editor' );
  1597. wp_enqueue_style( 'media-views' );
  1598. wp_plupload_default_settings();
  1599. require_once ABSPATH . WPINC . '/media-template.php';
  1600. add_action( 'admin_footer', 'wp_print_media_templates' );
  1601. add_action( 'wp_footer', 'wp_print_media_templates' );
  1602. do_action( 'wp_enqueue_media' );
  1603. }
  1604. /**
  1605. * Retrieve media attached to the passed post
  1606. *
  1607. * @since 3.6.0
  1608. *
  1609. * @param string $type (Mime) type of media desired
  1610. * @param int $post_id Post ID
  1611. * @return array Found attachments
  1612. */
  1613. function get_attached_media( $type, $post_id = 0 ) {
  1614. if ( ! $post = get_post( $post_id ) )
  1615. return;
  1616. $args = array(
  1617. 'post_parent' => $post->ID,
  1618. 'post_type' => 'attachment',
  1619. 'post_mime_type' => $type,
  1620. 'posts_per_page' => -1,
  1621. 'orderby' => 'menu_order',
  1622. 'order' => 'ASC',
  1623. );
  1624. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  1625. $children = get_children( $args );
  1626. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  1627. }
  1628. /**
  1629. * Retrieve audio attached to the passed post
  1630. *
  1631. * @since 3.6.0
  1632. *
  1633. * @param int $post_id Post ID
  1634. * @return array Found audio attachments
  1635. */
  1636. function get_attached_audio( $post_id = 0 ) {
  1637. return get_attached_media( 'audio', $post_id );
  1638. }
  1639. /**
  1640. * Retrieve video attached to the passed post
  1641. *
  1642. * @since 3.6.0
  1643. *
  1644. * @param int $post_id Post ID
  1645. * @return array Found video attachments
  1646. */
  1647. function get_attached_video( $post_id = 0 ) {
  1648. return get_attached_media( 'video', $post_id );
  1649. }
  1650. /**
  1651. * Extract and parse {media type} shortcodes or srcs from the passed content
  1652. *
  1653. * @since 3.6.0
  1654. *
  1655. * @param string $type Type of media: audio or video
  1656. * @param string $content A string which might contain media data.
  1657. * @param boolean $html Whether to return HTML or URLs
  1658. * @param int $limit Optional. The number of medias to return
  1659. * @return array A list of parsed shortcodes or extracted srcs
  1660. */
  1661. function get_content_media( $type, $content, $html = true, $limit = 0 ) {
  1662. $items = array();
  1663. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  1664. foreach ( $matches as $shortcode ) {
  1665. if ( $type === $shortcode[2] ) {
  1666. $count = 1;
  1667. $items[] = do_shortcode_tag( $shortcode );
  1668. if ( $limit > 0 && count( $items ) >= $limit )
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. if ( $html )
  1674. return $items;
  1675. $data = array();
  1676. foreach ( $items as $item ) {
  1677. preg_match_all( '#src=([\'"])(.+?)\1#is', $item, $src, PREG_SET_ORDER );
  1678. if ( ! empty( $src ) ) {
  1679. $srcs = array();
  1680. foreach ( $src as $s )
  1681. $srcs[] = $s[2];
  1682. $data[] = array_values( array_unique( $srcs ) );
  1683. }
  1684. }
  1685. return $data;
  1686. }
  1687. /**
  1688. * Check the content blob for an <{media type}>, <object>, <embed>, or <iframe>, in that order
  1689. * If no HTML tag is found, check the first line of the post for a URL
  1690. *
  1691. * @since 3.6.0
  1692. *
  1693. * @param string $type Type of media: audio or video
  1694. * @param string $content A string which might contain media data.
  1695. * @param int $limit Optional. The number of galleries to return
  1696. * @return array A list of found HTML media embeds and possibly a URL by itself
  1697. */
  1698. function get_embedded_media( $type, $content, $limit = 0 ) {
  1699. $html = array();
  1700. foreach ( array( $type, 'object', 'embed', 'iframe' ) as $tag ) {
  1701. if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
  1702. $html[] = $matches[0];
  1703. if ( $limit > 0 && count( $html ) >= $limit )
  1704. break;
  1705. }
  1706. }
  1707. if ( ! empty( $html ) && count( $html ) >= $limit )
  1708. return $html;
  1709. $lines = explode( "\n", trim( $content ) );
  1710. $line = trim( array_shift( $lines ) );
  1711. if ( 0 === stripos( $line, 'http' ) ) {
  1712. $html[] = $line;
  1713. }
  1714. return $html;
  1715. }
  1716. /**
  1717. * Extract the HTML or <source> srcs from the content's [audio]
  1718. *
  1719. * @since 3.6.0
  1720. *
  1721. * @param string $content A string which might contain audio data.
  1722. * @param boolean $html Whether to return HTML or URLs
  1723. * @return array A list of lists. Each item has a list of HTML or srcs corresponding
  1724. * to an [audio]'s HTML or primary src and specified fallbacks
  1725. */
  1726. function get_content_audio( $content, $html = true ) {
  1727. return get_content_media( 'audio', $content, $html );
  1728. }
  1729. /**
  1730. * Check the content blob for an <audio>, <object>, <embed>, or <iframe>, in that order
  1731. * If no HTML tag is found, check the first line of the post for a URL
  1732. *
  1733. * @since 3.6.0
  1734. *
  1735. * @param string $content A string which might contain audio data.
  1736. * @return array A list of found HTML audio embeds and possibly a URL by itself
  1737. */
  1738. function get_embedded_audio( $content ) {
  1739. return get_embedded_media( 'audio', $content );
  1740. }
  1741. /**
  1742. * Extract the HTML or <source> srcs from the content's [video]
  1743. *
  1744. * @since 3.6.0
  1745. *
  1746. * @param string $content A string which might contain video data.
  1747. * @param boolean $html Whether to return HTML or URLs
  1748. * @return array A list of lists. Each item has a list of HTML or srcs corresponding
  1749. * to a [video]'s HTML or primary src and specified fallbacks
  1750. */
  1751. function get_content_video( $content, $html = true ) {
  1752. return get_content_media( 'video', $content, $html );
  1753. }
  1754. /**
  1755. * Check the content blob for a <video>, <object>, <embed>, or <iframe>, in that order
  1756. * If no HTML tag is found, check the first line of the post for a URL
  1757. *
  1758. * @since 3.6.0
  1759. *
  1760. * @param string $content A string which might contain video data.
  1761. * @return array A list of found HTML video embeds and possibly a URL by itself
  1762. */
  1763. function get_embedded_video( $content ) {
  1764. return get_embedded_media( 'video', $content );
  1765. }
  1766. /**
  1767. * Return suitable HTML code for output based on the content related to the global $post
  1768. *
  1769. * @since 3.6.0
  1770. *
  1771. * @param string $type Required. 'audio' or 'video'
  1772. * @param WP_Post $post Optional. Used instead of global $post when passed.
  1773. * @param int $limit Optional. The number of medias to extract if content is scanned.
  1774. * @return string HTML for the media. Blank string if no media is found.
  1775. */
  1776. function get_the_post_format_media( $type, &$post = null, $limit = 0 ) {
  1777. global $wp_embed;
  1778. if ( empty( $post ) )
  1779. $post = get_post();
  1780. if ( empty( $post ) )
  1781. return '';
  1782. $cache_key = "media:{$type}";
  1783. if ( isset( $post->format_content[ $cache_key ] ) )
  1784. return $post->format_content[ $cache_key ];
  1785. if ( ! isset( $post->format_content ) )
  1786. $post->format_content = array();
  1787. $count = 1;
  1788. // these functions expect a reference, so we should make a copy of post content to avoid changing it
  1789. $content = $post->post_content;
  1790. $htmls = get_content_media( $type, $content, true, $limit );
  1791. if ( ! empty( $htmls ) ) {
  1792. $html = reset( $htmls );
  1793. $post->format_content[ $cache_key ] = $html;
  1794. return $post->format_content[ $cache_key ];
  1795. }
  1796. $embeds = get_embedded_media( $type, $content, 1 );
  1797. if ( ! empty( $embeds ) ) {
  1798. $embed = reset( $embeds );
  1799. if ( 0 === strpos( $embed, 'http' ) ) {
  1800. if ( strstr( $embed, home_url() ) ) {
  1801. $post->format_content[ $cache_key ] = do_shortcode( sprintf( '[%s src="%s"]', $type, $embed ) );
  1802. } else {
  1803. $post->format_content[ $cache_key ] = $wp_embed->autoembed( $embed );
  1804. }
  1805. } else {
  1806. $post->format_content[ $cache_key ] = $embed;
  1807. }
  1808. return $post->format_content[ $cache_key ];
  1809. }
  1810. $medias = call_user_func( 'get_attached_' . $type, $post->ID );
  1811. if ( ! empty( $medias ) ) {
  1812. $media = reset( $medias );
  1813. $url = wp_get_attachment_url( $media->ID );
  1814. $shortcode = sprintf( '[%s src="%s"]', $type, $url );
  1815. $post->format_content[ $cache_key ] = do_shortcode( $shortcode );
  1816. return $post->format_content[ $cache_key ];
  1817. }
  1818. return '';
  1819. }
  1820. /**
  1821. * Output the first video in the current (@global) post's content
  1822. *
  1823. * @since 3.6.0
  1824. *
  1825. */
  1826. function the_post_format_video() {
  1827. $null = null;
  1828. echo get_the_post_format_media( 'video', $null, 1 );
  1829. }
  1830. /**
  1831. * Output the first audio in the current (@global) post's content
  1832. *
  1833. * @since 3.6.0
  1834. *
  1835. */
  1836. function the_post_format_audio() {
  1837. $null = null;
  1838. echo get_the_post_format_media( 'audio', $null, 1 );
  1839. }
  1840. /**
  1841. * Retrieve images attached to the passed post
  1842. *
  1843. * @since 3.6.0
  1844. *
  1845. * @param int $post_id Optional. Post ID.
  1846. * @return array Found image attachments
  1847. */
  1848. function get_attached_images( $post_id = 0 ) {
  1849. return get_attached_media( 'image', $post_id );
  1850. }
  1851. /**
  1852. * Retrieve images attached to the passed post
  1853. *
  1854. * @since 3.6.0
  1855. *
  1856. * @param int $post_id Optional. Post ID.
  1857. * @return array Found image attachments
  1858. */
  1859. function get_attached_image_srcs( $post_id = 0 ) {
  1860. $children = get_attached_images( $post_id );
  1861. if ( empty( $children ) )
  1862. return array();
  1863. $srcs = array();
  1864. foreach ( $children as $attachment )
  1865. $srcs[] = wp_get_attachment_url( $attachment->ID );
  1866. return $srcs;
  1867. }
  1868. /**
  1869. * Check the content blob for images or image srcs
  1870. *
  1871. * @since 3.6.0
  1872. *
  1873. * @param string $content A string which might contain image data.
  1874. * @param boolean $html Whether to return HTML or URLs
  1875. * @param int $limit Optional. The number of image srcs to return
  1876. * @return array The found images or srcs
  1877. */
  1878. function get_content_images( $content, $html = true, $limit = 0 ) {
  1879. $tags = array();
  1880. $captions = array();
  1881. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  1882. foreach ( $matches as $shortcode ) {
  1883. if ( 'caption' === $shortcode[2] ) {
  1884. $captions[] = $shortcode[0];
  1885. if ( $html )
  1886. $tags[] = do_shortcode( $shortcode[0] );
  1887. }
  1888. if ( $limit > 0 && count( $tags ) >= $limit )
  1889. break;
  1890. }
  1891. }
  1892. foreach ( array( 'a', 'img' ) as $tag ) {
  1893. if ( preg_match_all( '#' . get_tag_regex( $tag ) . '#i', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  1894. foreach ( $matches as $node ) {
  1895. if ( ! strstr( $node[0], '<img ' ) )
  1896. continue;
  1897. $count = 1;
  1898. $found = false;
  1899. foreach ( $captions as $caption ) {
  1900. if ( strstr( $caption, $node[0] ) ) {
  1901. $found = true;
  1902. }
  1903. }
  1904. if ( ! $found )
  1905. $tags[] = $node[0];
  1906. if ( $limit > 0 && count( $tags ) >= $limit )
  1907. break 2;
  1908. }
  1909. }
  1910. }
  1911. if ( $html )
  1912. return $tags;
  1913. $srcs = array();
  1914. foreach ( $tags as $tag ) {
  1915. preg_match( '#src=([\'"])(.+?)\1#is', $tag, $src );
  1916. if ( ! empty( $src[2] ) ) {
  1917. $srcs[] = $src[2];
  1918. if ( $limit > 0 && count( $srcs ) >= $limit )
  1919. break;
  1920. }
  1921. }
  1922. return apply_filters( 'content_images', array_values( array_unique( $srcs ) ), $content );
  1923. }
  1924. /**
  1925. * Check the content blob for images or srcs and return the first
  1926. *
  1927. * @since 3.6.0
  1928. *
  1929. * @param string $content A string which might contain image data.
  1930. * @param boolean $html Whether to return HTML or URLs
  1931. * @return string The found data
  1932. */
  1933. function get_content_image( $content, $html = true ) {
  1934. $srcs = get_content_images( $content, $html, 1 );
  1935. if ( empty( $srcs ) )
  1936. return '';
  1937. return apply_filters( 'content_image', reset( $srcs ), $content );
  1938. }
  1939. /**
  1940. * Check the content blob for galleries and return their image srcs
  1941. *
  1942. * @since 3.6.0
  1943. *
  1944. * @param string $content A string which might contain image data.
  1945. * @param boolean $html Whether to return HTML or data
  1946. * @param int $limit Optional. The number of galleries to return
  1947. * @return array A list of galleries, which in turn are a list of their srcs in order
  1948. */
  1949. function get_content_galleries( $content, $html = true, $limit = 0 ) {
  1950. $galleries = array();
  1951. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  1952. foreach ( $matches as $shortcode ) {
  1953. if ( 'gallery' === $shortcode[2] ) {
  1954. $srcs = array();
  1955. $count = 1;
  1956. $data = shortcode_parse_atts( $shortcode[3] );
  1957. $gallery = do_shortcode_tag( $shortcode );
  1958. if ( $html ) {
  1959. $galleries[] = $gallery;
  1960. } else {
  1961. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  1962. if ( ! empty( $src ) ) {
  1963. foreach ( $src as $s )
  1964. $srcs[] = $s[2];
  1965. }
  1966. $data['src'] = array_values( array_unique( $srcs ) );
  1967. $galleries[] = $data;
  1968. }
  1969. if ( $limit > 0 && count( $galleries ) >= $limit )
  1970. break;
  1971. }
  1972. }
  1973. }
  1974. return apply_filters( 'content_galleries', $galleries, $content );
  1975. }
  1976. /**
  1977. * Retrieve galleries from the passed post's content
  1978. *
  1979. * @since 3.6.0
  1980. *
  1981. * @param int $post_id Optional. Post ID.
  1982. * @param boolean $html Whether to return HTML or data
  1983. * @return array A list of arrays, each containing gallery data and srcs parsed
  1984. * from the expanded shortcode
  1985. */
  1986. function get_post_galleries( $post_id = 0, $html = true ) {
  1987. if ( ! $post = get_post( $post_id ) )
  1988. return array();
  1989. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  1990. return array();
  1991. return get_content_galleries( $post->post_content, $html );
  1992. }
  1993. /**
  1994. * Retrieve the image srcs from galleries from a post's content, if present
  1995. *
  1996. * @since 3.6.0
  1997. *
  1998. * @param int $post_id Optional. Post ID.
  1999. * @return array A list of lists, each containing image srcs parsed
  2000. * from an expanded shortcode
  2001. */
  2002. function get_post_galleries_images( $post_id = 0 ) {
  2003. if ( ! $post = get_post( $post_id ) )
  2004. return array();
  2005. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  2006. return array();
  2007. $data = get_content_galleries( $post->post_content, false );
  2008. return wp_list_pluck( $data, 'src' );
  2009. }
  2010. /**
  2011. * Check a specified post's content for gallery and, if present, return the first
  2012. *
  2013. * @since 3.6.0
  2014. *
  2015. * @param int $post_id Optional. Post ID.
  2016. * @param boolean $html Whether to return HTML or data
  2017. * @return array Gallery data and srcs parsed from the expanded shortcode
  2018. */
  2019. function get_post_gallery( $post_id = 0, $html = true ) {
  2020. if ( ! $post = get_post( $post_id ) )
  2021. return array();
  2022. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  2023. return array();
  2024. $data = get_content_galleries( $post->post_content, $html, false, 1 );
  2025. return reset( $data );
  2026. }
  2027. /**
  2028. * Output the first gallery in the current (@global) $post
  2029. *
  2030. * @since 3.6.0
  2031. */
  2032. function the_post_format_gallery() {
  2033. echo get_post_gallery();
  2034. }
  2035. /**
  2036. * Check a post's content for galleries and return the image srcs for the first found gallery
  2037. *
  2038. * @since 3.6.0
  2039. *
  2040. * @param int $post_id Optional. Post ID.
  2041. * @return array A list of a gallery's image srcs in order
  2042. */
  2043. function get_post_gallery_images( $post_id = 0 ) {
  2044. $gallery = get_post_gallery( $post_id, false );
  2045. if ( empty( $gallery['src'] ) )
  2046. return array();
  2047. return $gallery['src'];
  2048. }
  2049. /**
  2050. * Return the first image in the current (@global) post's content
  2051. *
  2052. * @since 3.6.0
  2053. *
  2054. * @param string $attached_size If an attached image is found, the size to display it.
  2055. * @param WP_Post $post Optional. Used instead of global $post when passed.
  2056. * @return string HTML for the image. Blank string if no image is found.
  2057. */
  2058. function get_the_post_format_image( $attached_size = 'full', &$post = null ) {
  2059. if ( empty( $post ) )
  2060. $post = get_post();
  2061. if ( empty( $post ) )
  2062. return '';
  2063. $cache_key = "image:{$attached_size}";
  2064. if ( isset( $post->format_content[ $cache_key ] ) )
  2065. return $post->format_content[ $cache_key ];
  2066. if ( ! isset( $post->format_content ) )
  2067. $post->format_content = array();
  2068. $matched = false;
  2069. $link_fmt = '%s';
  2070. $medias = get_attached_images( $post->ID );
  2071. if ( ! empty( $medias ) ) {
  2072. $media = reset( $medias );
  2073. $sizes = get_intermediate_image_sizes();
  2074. $sizes[] = 'full'; // Add original image source.
  2075. $urls = array();
  2076. foreach ( $sizes as $size ) {
  2077. $image = wp_get_attachment_image_src( $media->ID, $size );
  2078. if ( $image )
  2079. $urls[] = reset( $image );
  2080. }
  2081. // Add media permalink.
  2082. $urls[] = get_attachment_link( $media->ID );
  2083. $count = 1;
  2084. $content = $post->post_content;
  2085. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  2086. foreach ( $matches as $shortcode ) {
  2087. if ( 'caption' === $shortcode[2] ) {
  2088. foreach ( $urls as $url ) {
  2089. if ( strstr( $shortcode[0], $url ) ) {
  2090. if ( ! $matched )
  2091. $matched = do_shortcode( $shortcode[0] );
  2092. // $content = str_replace( $shortcode[0], '', $content, $count );
  2093. }
  2094. }
  2095. }
  2096. }
  2097. }
  2098. foreach ( array( 'a', 'img' ) as $tag ) {
  2099. if ( preg_match_all( '#' . get_tag_regex( $tag ) . '#', $content, $matches, PREG_SET_ORDER ) && ! empty( $matches ) ) {
  2100. foreach ( $matches as $match ) {
  2101. foreach ( $urls as $url ) {
  2102. if ( strstr( $match[0], $url ) ) {
  2103. if ( ! $matched )
  2104. $matched = $match[0];
  2105. // $content = str_replace( $match[0], '', $content, $count );
  2106. }
  2107. }
  2108. }
  2109. }
  2110. }
  2111. if ( ! $matched ) {
  2112. $image = wp_get_attachment_image( $media->ID, $attached_size );
  2113. $post->format_content[ $cache_key ] = sprintf( $link_fmt, $image );
  2114. } else {
  2115. $post->format_content[ $cache_key ] = $matched;
  2116. if ( ! empty( $meta['url'] ) && false === stripos( $matched, '<a ' ) )
  2117. $post->format_content[ $cache_key ] = sprintf( $link_fmt, $matched );
  2118. }
  2119. return $post->format_content[ $cache_key ];
  2120. }
  2121. $content = $post->post_content;
  2122. $htmls = get_content_images( $content, true, 1 );
  2123. if ( ! empty( $htmls ) ) {
  2124. $html = reset( $htmls );
  2125. $attachment_id = img_html_to_post_id( $html, $matched_html );
  2126. if ( $attachment_id && $matched_html )
  2127. $html = str_replace( $matched_html, wp_get_attachment_image( $attachment_id, $attached_size ), $html );
  2128. $post->format_content[ $cache_key ] = sprintf( $link_fmt, $html );
  2129. return $post->format_content[ $cache_key ];
  2130. }
  2131. return '';
  2132. }
  2133. /**
  2134. * Output the first image in the current (@global) post's content
  2135. *
  2136. * @since 3.6.0
  2137. *
  2138. * @param string $attached_size If an attached image is found, the size to display it.
  2139. */
  2140. function the_post_format_image( $attached_size = 'full' ) {
  2141. echo get_the_post_format_image( $attached_size );
  2142. }
  2143. /**
  2144. * Retrieve the post id for an attachment file URL
  2145. *
  2146. * @since 3.6.0
  2147. *
  2148. * @param string $url Permalink to check.
  2149. * @return int Post ID, or 0 on failure.
  2150. */
  2151. function attachment_url_to_postid( $url ) {
  2152. global $wpdb;
  2153. if ( preg_match( '#\.[a-zA-Z0-9]+$#', $url ) ) {
  2154. $id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' " .
  2155. "AND guid = %s", $url ) );
  2156. if ( ! empty( $id ) )
  2157. return (int) $id;
  2158. }
  2159. return 0;
  2160. }
  2161. /**
  2162. * Retrieve the attachment post id from HTML containing an image.
  2163. *
  2164. * @since 3.6.0
  2165. *
  2166. * @param string $html The html, possibly with an image
  2167. * @param string $matched_html Passed by reference, will be set to to the matched img string
  2168. * @return int The attachment id if found, or 0.
  2169. */
  2170. function img_html_to_post_id( $html, &$matched_html = null ) {
  2171. $attachment_id = 0;
  2172. // Look for an <img /> tag
  2173. if ( ! preg_match( '#' . get_tag_regex( 'img' ) . '#i', $html, $matches ) || empty( $matches ) )
  2174. return $attachment_id;
  2175. $matched_html = $matches[0];
  2176. // Look for attributes.
  2177. if ( ! preg_match_all( '#(src|class)=([\'"])(.+?)\2#is', $matched_html, $matches ) || empty( $matches ) )
  2178. return $attachment_id;
  2179. $attr = array();
  2180. foreach ( $matches[1] as $key => $attribute_name )
  2181. $attr[ $attribute_name ] = $matches[3][ $key ];
  2182. if ( ! empty( $attr['class'] ) && false !== strpos( $attr['class'], 'wp-image-' ) )
  2183. if ( preg_match( '#wp-image-([0-9]+)#i', $attr['class'], $matches ) )
  2184. $attachment_id = absint( $matches[1] );
  2185. if ( ! $attachment_id && ! empty( $attr['src'] ) )
  2186. $attachment_id = attachment_url_to_postid( $attr['src'] );
  2187. return $attachment_id;
  2188. }