media.php 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953
  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. * @subpackage Media
  7. */
  8. /**
  9. * Retrieve additional image sizes.
  10. *
  11. * @since 4.7.0
  12. *
  13. * @global array $_wp_additional_image_sizes
  14. *
  15. * @return array Additional images size data.
  16. */
  17. function wp_get_additional_image_sizes() {
  18. global $_wp_additional_image_sizes;
  19. if ( ! $_wp_additional_image_sizes ) {
  20. $_wp_additional_image_sizes = array();
  21. }
  22. return $_wp_additional_image_sizes;
  23. }
  24. /**
  25. * Scale down the default size of an image.
  26. *
  27. * This is so that the image is a better fit for the editor and theme.
  28. *
  29. * The `$size` parameter accepts either an array or a string. The supported string
  30. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  31. * 128 width and 96 height in pixels. Also supported for the string value is
  32. * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
  33. * than the supported will result in the content_width size or 500 if that is
  34. * not set.
  35. *
  36. * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
  37. * called on the calculated array for width and height, respectively. The second
  38. * parameter will be the value that was in the $size parameter. The returned
  39. * type for the hook is an array with the width as the first element and the
  40. * height as the second element.
  41. *
  42. * @since 2.5.0
  43. *
  44. * @global int $content_width
  45. *
  46. * @param int $width Width of the image in pixels.
  47. * @param int $height Height of the image in pixels.
  48. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array
  49. * of width and height values in pixels (in that order).
  50. * Default 'medium'.
  51. * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
  52. * (like inserting into an editor). Default null.
  53. * @return array Width and height of what the result image should resize to.
  54. */
  55. function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  56. global $content_width;
  57. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  58. if ( ! $context )
  59. $context = is_admin() ? 'edit' : 'display';
  60. if ( is_array($size) ) {
  61. $max_width = $size[0];
  62. $max_height = $size[1];
  63. }
  64. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  65. $max_width = intval(get_option('thumbnail_size_w'));
  66. $max_height = intval(get_option('thumbnail_size_h'));
  67. // last chance thumbnail size defaults
  68. if ( !$max_width && !$max_height ) {
  69. $max_width = 128;
  70. $max_height = 96;
  71. }
  72. }
  73. elseif ( $size == 'medium' ) {
  74. $max_width = intval(get_option('medium_size_w'));
  75. $max_height = intval(get_option('medium_size_h'));
  76. }
  77. elseif ( $size == 'medium_large' ) {
  78. $max_width = intval( get_option( 'medium_large_size_w' ) );
  79. $max_height = intval( get_option( 'medium_large_size_h' ) );
  80. if ( intval( $content_width ) > 0 ) {
  81. $max_width = min( intval( $content_width ), $max_width );
  82. }
  83. }
  84. elseif ( $size == 'large' ) {
  85. /*
  86. * We're inserting a large size image into the editor. If it's a really
  87. * big image we'll scale it down to fit reasonably within the editor
  88. * itself, and within the theme's content width if it's known. The user
  89. * can resize it in the editor if they wish.
  90. */
  91. $max_width = intval(get_option('large_size_w'));
  92. $max_height = intval(get_option('large_size_h'));
  93. if ( intval($content_width) > 0 ) {
  94. $max_width = min( intval($content_width), $max_width );
  95. }
  96. } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  97. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  98. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  99. // Only in admin. Assume that theme authors know what they're doing.
  100. if ( intval( $content_width ) > 0 && 'edit' === $context ) {
  101. $max_width = min( intval( $content_width ), $max_width );
  102. }
  103. }
  104. // $size == 'full' has no constraint
  105. else {
  106. $max_width = $width;
  107. $max_height = $height;
  108. }
  109. /**
  110. * Filters the maximum image size dimensions for the editor.
  111. *
  112. * @since 2.5.0
  113. *
  114. * @param array $max_image_size An array with the width as the first element,
  115. * and the height as the second element.
  116. * @param string|array $size Size of what the result image should be.
  117. * @param string $context The context the image is being resized for.
  118. * Possible values are 'display' (like in a theme)
  119. * or 'edit' (like inserting into an editor).
  120. */
  121. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  122. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  123. }
  124. /**
  125. * Retrieve width and height attributes using given width and height values.
  126. *
  127. * Both attributes are required in the sense that both parameters must have a
  128. * value, but are optional in that if you set them to false or null, then they
  129. * will not be added to the returned string.
  130. *
  131. * You can set the value using a string, but it will only take numeric values.
  132. * If you wish to put 'px' after the numbers, then it will be stripped out of
  133. * the return.
  134. *
  135. * @since 2.5.0
  136. *
  137. * @param int|string $width Image width in pixels.
  138. * @param int|string $height Image height in pixels.
  139. * @return string HTML attributes for width and, or height.
  140. */
  141. function image_hwstring( $width, $height ) {
  142. $out = '';
  143. if ($width)
  144. $out .= 'width="'.intval($width).'" ';
  145. if ($height)
  146. $out .= 'height="'.intval($height).'" ';
  147. return $out;
  148. }
  149. /**
  150. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  151. *
  152. * Array with image url, width, height, and whether is intermediate size, in
  153. * that order is returned on success is returned. $is_intermediate is true if
  154. * $url is a resized image, false if it is the original.
  155. *
  156. * The URL might be the original image, or it might be a resized version. This
  157. * function won't create a new resized copy, it will just return an already
  158. * resized one if it exists.
  159. *
  160. * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
  161. * resizing services for images. The hook must return an array with the same
  162. * elements that are returned in the function. The first element being the URL
  163. * to the new image that was resized.
  164. *
  165. * @since 2.5.0
  166. *
  167. * @param int $id Attachment ID for image.
  168. * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
  169. * or an array of width and height values in pixels (in that order).
  170. * Default 'medium'.
  171. * @return false|array Array containing the image URL, width, height, and boolean for whether
  172. * the image is an intermediate size. False on failure.
  173. */
  174. function image_downsize( $id, $size = 'medium' ) {
  175. $is_image = wp_attachment_is_image( $id );
  176. /**
  177. * Filters whether to preempt the output of image_downsize().
  178. *
  179. * Passing a truthy value to the filter will effectively short-circuit
  180. * down-sizing the image, returning that value as output instead.
  181. *
  182. * @since 2.5.0
  183. *
  184. * @param bool $downsize Whether to short-circuit the image downsize. Default false.
  185. * @param int $id Attachment ID for image.
  186. * @param array|string $size Size of image. Image size or array of width and height values (in that order).
  187. * Default 'medium'.
  188. */
  189. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
  190. return $out;
  191. }
  192. $img_url = wp_get_attachment_url($id);
  193. $meta = wp_get_attachment_metadata($id);
  194. $width = $height = 0;
  195. $is_intermediate = false;
  196. $img_url_basename = wp_basename($img_url);
  197. // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
  198. // Otherwise, a non-image type could be returned.
  199. if ( ! $is_image ) {
  200. if ( ! empty( $meta['sizes'] ) ) {
  201. $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
  202. $img_url_basename = $meta['sizes']['full']['file'];
  203. $width = $meta['sizes']['full']['width'];
  204. $height = $meta['sizes']['full']['height'];
  205. } else {
  206. return false;
  207. }
  208. }
  209. // try for a new style intermediate size
  210. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  211. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  212. $width = $intermediate['width'];
  213. $height = $intermediate['height'];
  214. $is_intermediate = true;
  215. }
  216. elseif ( $size == 'thumbnail' ) {
  217. // fall back to the old thumbnail
  218. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  219. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  220. $width = $info[0];
  221. $height = $info[1];
  222. $is_intermediate = true;
  223. }
  224. }
  225. if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
  226. // any other type: use the real image
  227. $width = $meta['width'];
  228. $height = $meta['height'];
  229. }
  230. if ( $img_url) {
  231. // we have the actual image size, but might need to further constrain it if content_width is narrower
  232. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  233. return array( $img_url, $width, $height, $is_intermediate );
  234. }
  235. return false;
  236. }
  237. /**
  238. * Register a new image size.
  239. *
  240. * Cropping behavior for the image size is dependent on the value of $crop:
  241. * 1. If false (default), images will be scaled, not cropped.
  242. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  243. * - x_crop_position accepts 'left' 'center', or 'right'.
  244. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  245. * Images will be cropped to the specified dimensions within the defined crop area.
  246. * 3. If true, images will be cropped to the specified dimensions using center positions.
  247. *
  248. * @since 2.9.0
  249. *
  250. * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
  251. *
  252. * @param string $name Image size identifier.
  253. * @param int $width Image width in pixels.
  254. * @param int $height Image height in pixels.
  255. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  256. * An array can specify positioning of the crop area. Default false.
  257. */
  258. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  259. global $_wp_additional_image_sizes;
  260. $_wp_additional_image_sizes[ $name ] = array(
  261. 'width' => absint( $width ),
  262. 'height' => absint( $height ),
  263. 'crop' => $crop,
  264. );
  265. }
  266. /**
  267. * Check if an image size exists.
  268. *
  269. * @since 3.9.0
  270. *
  271. * @param string $name The image size to check.
  272. * @return bool True if the image size exists, false if not.
  273. */
  274. function has_image_size( $name ) {
  275. $sizes = wp_get_additional_image_sizes();
  276. return isset( $sizes[ $name ] );
  277. }
  278. /**
  279. * Remove a new image size.
  280. *
  281. * @since 3.9.0
  282. *
  283. * @global array $_wp_additional_image_sizes
  284. *
  285. * @param string $name The image size to remove.
  286. * @return bool True if the image size was successfully removed, false on failure.
  287. */
  288. function remove_image_size( $name ) {
  289. global $_wp_additional_image_sizes;
  290. if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
  291. unset( $_wp_additional_image_sizes[ $name ] );
  292. return true;
  293. }
  294. return false;
  295. }
  296. /**
  297. * Registers an image size for the post thumbnail.
  298. *
  299. * @since 2.9.0
  300. *
  301. * @see add_image_size() for details on cropping behavior.
  302. *
  303. * @param int $width Image width in pixels.
  304. * @param int $height Image height in pixels.
  305. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  306. * An array can specify positioning of the crop area. Default false.
  307. */
  308. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  309. add_image_size( 'post-thumbnail', $width, $height, $crop );
  310. }
  311. /**
  312. * Gets an img tag for an image attachment, scaling it down if requested.
  313. *
  314. * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
  315. * image without having to use regular expressions on the HTML content. The
  316. * parameters are: what WordPress will use for the class, the Attachment ID,
  317. * image align value, and the size the image should be.
  318. *
  319. * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
  320. * further manipulated by a plugin to change all attribute values and even HTML
  321. * content.
  322. *
  323. * @since 2.5.0
  324. *
  325. * @param int $id Attachment ID.
  326. * @param string $alt Image Description for the alt attribute.
  327. * @param string $title Image Description for the title attribute.
  328. * @param string $align Part of the class name for aligning the image.
  329. * @param string|array $size Optional. Registered image size to retrieve a tag for. Accepts any
  330. * valid image size, or an array of width and height values in pixels
  331. * (in that order). Default 'medium'.
  332. * @return string HTML IMG element for given image attachment
  333. */
  334. function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
  335. list( $img_src, $width, $height ) = image_downsize($id, $size);
  336. $hwstring = image_hwstring($width, $height);
  337. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  338. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  339. /**
  340. * Filters the value of the attachment's image tag class attribute.
  341. *
  342. * @since 2.6.0
  343. *
  344. * @param string $class CSS class name or space-separated list of classes.
  345. * @param int $id Attachment ID.
  346. * @param string $align Part of the class name for aligning the image.
  347. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  348. * Default 'medium'.
  349. */
  350. $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
  351. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  352. /**
  353. * Filters the HTML content for the image tag.
  354. *
  355. * @since 2.6.0
  356. *
  357. * @param string $html HTML content for the image.
  358. * @param int $id Attachment ID.
  359. * @param string $alt Alternate text.
  360. * @param string $title Attachment title.
  361. * @param string $align Part of the class name for aligning the image.
  362. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  363. * Default 'medium'.
  364. */
  365. return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  366. }
  367. /**
  368. * Calculates the new dimensions for a down-sampled image.
  369. *
  370. * If either width or height are empty, no constraint is applied on
  371. * that dimension.
  372. *
  373. * @since 2.5.0
  374. *
  375. * @param int $current_width Current width of the image.
  376. * @param int $current_height Current height of the image.
  377. * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
  378. * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
  379. * @return array First item is the width, the second item is the height.
  380. */
  381. function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
  382. if ( !$max_width && !$max_height )
  383. return array( $current_width, $current_height );
  384. $width_ratio = $height_ratio = 1.0;
  385. $did_width = $did_height = false;
  386. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  387. $width_ratio = $max_width / $current_width;
  388. $did_width = true;
  389. }
  390. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  391. $height_ratio = $max_height / $current_height;
  392. $did_height = true;
  393. }
  394. // Calculate the larger/smaller ratios
  395. $smaller_ratio = min( $width_ratio, $height_ratio );
  396. $larger_ratio = max( $width_ratio, $height_ratio );
  397. if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
  398. // The larger ratio is too big. It would result in an overflow.
  399. $ratio = $smaller_ratio;
  400. } else {
  401. // The larger ratio fits, and is likely to be a more "snug" fit.
  402. $ratio = $larger_ratio;
  403. }
  404. // Very small dimensions may result in 0, 1 should be the minimum.
  405. $w = max ( 1, (int) round( $current_width * $ratio ) );
  406. $h = max ( 1, (int) round( $current_height * $ratio ) );
  407. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  408. // 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.
  409. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  410. // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
  411. if ( $did_width && $w == $max_width - 1 ) {
  412. $w = $max_width; // Round it up
  413. }
  414. // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
  415. if ( $did_height && $h == $max_height - 1 ) {
  416. $h = $max_height; // Round it up
  417. }
  418. /**
  419. * Filters dimensions to constrain down-sampled images to.
  420. *
  421. * @since 4.1.0
  422. *
  423. * @param array $dimensions The image width and height.
  424. * @param int $current_width The current width of the image.
  425. * @param int $current_height The current height of the image.
  426. * @param int $max_width The maximum width permitted.
  427. * @param int $max_height The maximum height permitted.
  428. */
  429. return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
  430. }
  431. /**
  432. * Retrieves calculated resize dimensions for use in WP_Image_Editor.
  433. *
  434. * Calculates dimensions and coordinates for a resized image that fits
  435. * within a specified width and height.
  436. *
  437. * Cropping behavior is dependent on the value of $crop:
  438. * 1. If false (default), images will not be cropped.
  439. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  440. * - x_crop_position accepts 'left' 'center', or 'right'.
  441. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  442. * Images will be cropped to the specified dimensions within the defined crop area.
  443. * 3. If true, images will be cropped to the specified dimensions using center positions.
  444. *
  445. * @since 2.5.0
  446. *
  447. * @param int $orig_w Original width in pixels.
  448. * @param int $orig_h Original height in pixels.
  449. * @param int $dest_w New width in pixels.
  450. * @param int $dest_h New height in pixels.
  451. * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
  452. * An array can specify positioning of the crop area. Default false.
  453. * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
  454. */
  455. function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
  456. if ($orig_w <= 0 || $orig_h <= 0)
  457. return false;
  458. // at least one of dest_w or dest_h must be specific
  459. if ($dest_w <= 0 && $dest_h <= 0)
  460. return false;
  461. /**
  462. * Filters whether to preempt calculating the image resize dimensions.
  463. *
  464. * Passing a non-null value to the filter will effectively short-circuit
  465. * image_resize_dimensions(), returning that value instead.
  466. *
  467. * @since 3.4.0
  468. *
  469. * @param null|mixed $null Whether to preempt output of the resize dimensions.
  470. * @param int $orig_w Original width in pixels.
  471. * @param int $orig_h Original height in pixels.
  472. * @param int $dest_w New width in pixels.
  473. * @param int $dest_h New height in pixels.
  474. * @param bool|array $crop Whether to crop image to specified width and height or resize.
  475. * An array can specify positioning of the crop area. Default false.
  476. */
  477. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  478. if ( null !== $output )
  479. return $output;
  480. if ( $crop ) {
  481. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  482. $aspect_ratio = $orig_w / $orig_h;
  483. $new_w = min($dest_w, $orig_w);
  484. $new_h = min($dest_h, $orig_h);
  485. if ( ! $new_w ) {
  486. $new_w = (int) round( $new_h * $aspect_ratio );
  487. }
  488. if ( ! $new_h ) {
  489. $new_h = (int) round( $new_w / $aspect_ratio );
  490. }
  491. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  492. $crop_w = round($new_w / $size_ratio);
  493. $crop_h = round($new_h / $size_ratio);
  494. if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
  495. $crop = array( 'center', 'center' );
  496. }
  497. list( $x, $y ) = $crop;
  498. if ( 'left' === $x ) {
  499. $s_x = 0;
  500. } elseif ( 'right' === $x ) {
  501. $s_x = $orig_w - $crop_w;
  502. } else {
  503. $s_x = floor( ( $orig_w - $crop_w ) / 2 );
  504. }
  505. if ( 'top' === $y ) {
  506. $s_y = 0;
  507. } elseif ( 'bottom' === $y ) {
  508. $s_y = $orig_h - $crop_h;
  509. } else {
  510. $s_y = floor( ( $orig_h - $crop_h ) / 2 );
  511. }
  512. } else {
  513. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  514. $crop_w = $orig_w;
  515. $crop_h = $orig_h;
  516. $s_x = 0;
  517. $s_y = 0;
  518. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  519. }
  520. // if the resulting image would be the same size or larger we don't want to resize it
  521. if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
  522. return false;
  523. }
  524. // the return array matches the parameters to imagecopyresampled()
  525. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  526. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  527. }
  528. /**
  529. * Resizes an image to make a thumbnail or intermediate size.
  530. *
  531. * The returned array has the file size, the image width, and image height. The
  532. * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
  533. * values of the returned array. The only parameter is the resized file path.
  534. *
  535. * @since 2.5.0
  536. *
  537. * @param string $file File path.
  538. * @param int $width Image width.
  539. * @param int $height Image height.
  540. * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
  541. * Default false.
  542. * @return false|array False, if no image was created. Metadata array on success.
  543. */
  544. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  545. if ( $width || $height ) {
  546. $editor = wp_get_image_editor( $file );
  547. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  548. return false;
  549. $resized_file = $editor->save();
  550. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  551. unset( $resized_file['path'] );
  552. return $resized_file;
  553. }
  554. }
  555. return false;
  556. }
  557. /**
  558. * Helper function to test if aspect ratios for two images match.
  559. *
  560. * @since 4.6.0
  561. *
  562. * @param int $source_width Width of the first image in pixels.
  563. * @param int $source_height Height of the first image in pixels.
  564. * @param int $target_width Width of the second image in pixels.
  565. * @param int $target_height Height of the second image in pixels.
  566. * @return bool True if aspect ratios match within 1px. False if not.
  567. */
  568. function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
  569. /*
  570. * To test for varying crops, we constrain the dimensions of the larger image
  571. * to the dimensions of the smaller image and see if they match.
  572. */
  573. if ( $source_width > $target_width ) {
  574. $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
  575. $expected_size = array( $target_width, $target_height );
  576. } else {
  577. $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
  578. $expected_size = array( $source_width, $source_height );
  579. }
  580. // If the image dimensions are within 1px of the expected size, we consider it a match.
  581. $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
  582. return $matched;
  583. }
  584. /**
  585. * Retrieves the image's intermediate size (resized) path, width, and height.
  586. *
  587. * The $size parameter can be an array with the width and height respectively.
  588. * If the size matches the 'sizes' metadata array for width and height, then it
  589. * will be used. If there is no direct match, then the nearest image size larger
  590. * than the specified size will be used. If nothing is found, then the function
  591. * will break out and return false.
  592. *
  593. * The metadata 'sizes' is used for compatible sizes that can be used for the
  594. * parameter $size value.
  595. *
  596. * The url path will be given, when the $size parameter is a string.
  597. *
  598. * If you are passing an array for the $size, you should consider using
  599. * add_image_size() so that a cropped version is generated. It's much more
  600. * efficient than having to find the closest-sized image and then having the
  601. * browser scale down the image.
  602. *
  603. * @since 2.5.0
  604. *
  605. * @param int $post_id Attachment ID.
  606. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array
  607. * of width and height values in pixels (in that order).
  608. * Default 'thumbnail'.
  609. * @return false|array $data {
  610. * Array of file relative path, width, and height on success. Additionally includes absolute
  611. * path and URL if registered size is passed to $size parameter. False on failure.
  612. *
  613. * @type string $file Image's path relative to uploads directory
  614. * @type int $width Width of image
  615. * @type int $height Height of image
  616. * @type string $path Image's absolute filesystem path.
  617. * @type string $url Image's URL.
  618. * }
  619. */
  620. function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
  621. if ( ! $size || ! is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) || empty( $imagedata['sizes'] ) ) {
  622. return false;
  623. }
  624. $data = array();
  625. // Find the best match when '$size' is an array.
  626. if ( is_array( $size ) ) {
  627. $candidates = array();
  628. if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
  629. $imagedata['height'] = $imagedata['sizes']['full']['height'];
  630. $imagedata['width'] = $imagedata['sizes']['full']['width'];
  631. }
  632. foreach ( $imagedata['sizes'] as $_size => $data ) {
  633. // If there's an exact match to an existing image size, short circuit.
  634. if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
  635. $candidates[ $data['width'] * $data['height'] ] = $data;
  636. break;
  637. }
  638. // If it's not an exact match, consider larger sizes with the same aspect ratio.
  639. if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
  640. // If '0' is passed to either size, we test ratios against the original file.
  641. if ( 0 === $size[0] || 0 === $size[1] ) {
  642. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
  643. } else {
  644. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
  645. }
  646. if ( $same_ratio ) {
  647. $candidates[ $data['width'] * $data['height'] ] = $data;
  648. }
  649. }
  650. }
  651. if ( ! empty( $candidates ) ) {
  652. // Sort the array by size if we have more than one candidate.
  653. if ( 1 < count( $candidates ) ) {
  654. ksort( $candidates );
  655. }
  656. $data = array_shift( $candidates );
  657. /*
  658. * When the size requested is smaller than the thumbnail dimensions, we
  659. * fall back to the thumbnail size to maintain backwards compatibility with
  660. * pre 4.6 versions of WordPress.
  661. */
  662. } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
  663. $data = $imagedata['sizes']['thumbnail'];
  664. } else {
  665. return false;
  666. }
  667. // Constrain the width and height attributes to the requested values.
  668. list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  669. } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
  670. $data = $imagedata['sizes'][ $size ];
  671. }
  672. // If we still don't have a match at this point, return false.
  673. if ( empty( $data ) ) {
  674. return false;
  675. }
  676. // include the full filesystem path of the intermediate file
  677. if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
  678. $file_url = wp_get_attachment_url($post_id);
  679. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  680. $data['url'] = path_join( dirname($file_url), $data['file'] );
  681. }
  682. /**
  683. * Filters the output of image_get_intermediate_size()
  684. *
  685. * @since 4.4.0
  686. *
  687. * @see image_get_intermediate_size()
  688. *
  689. * @param array $data Array of file relative path, width, and height on success. May also include
  690. * file absolute path and URL.
  691. * @param int $post_id The post_id of the image attachment
  692. * @param string|array $size Registered image size or flat array of initially-requested height and width
  693. * dimensions (in that order).
  694. */
  695. return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
  696. }
  697. /**
  698. * Gets the available intermediate image sizes.
  699. *
  700. * @since 3.0.0
  701. *
  702. * @return array Returns a filtered array of image size strings.
  703. */
  704. function get_intermediate_image_sizes() {
  705. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  706. $image_sizes = array('thumbnail', 'medium', 'medium_large', 'large'); // Standard sizes
  707. if ( ! empty( $_wp_additional_image_sizes ) ) {
  708. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  709. }
  710. /**
  711. * Filters the list of intermediate image sizes.
  712. *
  713. * @since 2.5.0
  714. *
  715. * @param array $image_sizes An array of intermediate image sizes. Defaults
  716. * are 'thumbnail', 'medium', 'medium_large', 'large'.
  717. */
  718. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  719. }
  720. /**
  721. * Retrieve an image to represent an attachment.
  722. *
  723. * A mime icon for files, thumbnail or intermediate size for images.
  724. *
  725. * The returned array contains four values: the URL of the attachment image src,
  726. * the width of the image file, the height of the image file, and a boolean
  727. * representing whether the returned array describes an intermediate (generated)
  728. * image size or the original, full-sized upload.
  729. *
  730. * @since 2.5.0
  731. *
  732. * @param int $attachment_id Image attachment ID.
  733. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  734. * and height values in pixels (in that order). Default 'thumbnail'.
  735. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  736. * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
  737. */
  738. function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
  739. // get a thumbnail or intermediate image if there is one
  740. $image = image_downsize( $attachment_id, $size );
  741. if ( ! $image ) {
  742. $src = false;
  743. if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
  744. /** This filter is documented in wp-includes/post.php */
  745. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  746. $src_file = $icon_dir . '/' . wp_basename( $src );
  747. @list( $width, $height ) = getimagesize( $src_file );
  748. }
  749. if ( $src && $width && $height ) {
  750. $image = array( $src, $width, $height );
  751. }
  752. }
  753. /**
  754. * Filters the image src result.
  755. *
  756. * @since 4.3.0
  757. *
  758. * @param array|false $image Either array with src, width & height, icon src, or false.
  759. * @param int $attachment_id Image attachment ID.
  760. * @param string|array $size Size of image. Image size or array of width and height values
  761. * (in that order). Default 'thumbnail'.
  762. * @param bool $icon Whether the image should be treated as an icon. Default false.
  763. */
  764. return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
  765. }
  766. /**
  767. * Get an HTML img element representing an image attachment
  768. *
  769. * While `$size` will accept an array, it is better to register a size with
  770. * add_image_size() so that a cropped version is generated. It's much more
  771. * efficient than having to find the closest-sized image and then having the
  772. * browser scale down the image.
  773. *
  774. * @since 2.5.0
  775. *
  776. * @param int $attachment_id Image attachment ID.
  777. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  778. * and height values in pixels (in that order). Default 'thumbnail'.
  779. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  780. * @param string|array $attr Optional. Attributes for the image markup. Default empty.
  781. * @return string HTML img element or empty string on failure.
  782. */
  783. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  784. $html = '';
  785. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  786. if ( $image ) {
  787. list($src, $width, $height) = $image;
  788. $hwstring = image_hwstring($width, $height);
  789. $size_class = $size;
  790. if ( is_array( $size_class ) ) {
  791. $size_class = join( 'x', $size_class );
  792. }
  793. $attachment = get_post($attachment_id);
  794. $default_attr = array(
  795. 'src' => $src,
  796. 'class' => "attachment-$size_class size-$size_class",
  797. 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
  798. );
  799. $attr = wp_parse_args( $attr, $default_attr );
  800. // Generate 'srcset' and 'sizes' if not already present.
  801. if ( empty( $attr['srcset'] ) ) {
  802. $image_meta = wp_get_attachment_metadata( $attachment_id );
  803. if ( is_array( $image_meta ) ) {
  804. $size_array = array( absint( $width ), absint( $height ) );
  805. $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
  806. $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
  807. if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
  808. $attr['srcset'] = $srcset;
  809. if ( empty( $attr['sizes'] ) ) {
  810. $attr['sizes'] = $sizes;
  811. }
  812. }
  813. }
  814. }
  815. /**
  816. * Filters the list of attachment image attributes.
  817. *
  818. * @since 2.8.0
  819. *
  820. * @param array $attr Attributes for the image markup.
  821. * @param WP_Post $attachment Image attachment post.
  822. * @param string|array $size Requested size. Image size or array of width and height values
  823. * (in that order). Default 'thumbnail'.
  824. */
  825. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
  826. $attr = array_map( 'esc_attr', $attr );
  827. $html = rtrim("<img $hwstring");
  828. foreach ( $attr as $name => $value ) {
  829. $html .= " $name=" . '"' . $value . '"';
  830. }
  831. $html .= ' />';
  832. }
  833. return $html;
  834. }
  835. /**
  836. * Get the URL of an image attachment.
  837. *
  838. * @since 4.4.0
  839. *
  840. * @param int $attachment_id Image attachment ID.
  841. * @param string|array $size Optional. Image size to retrieve. Accepts any valid image size, or an array
  842. * of width and height values in pixels (in that order). Default 'thumbnail'.
  843. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  844. * @return string|false Attachment URL or false if no image is available.
  845. */
  846. function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
  847. $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
  848. return isset( $image['0'] ) ? $image['0'] : false;
  849. }
  850. /**
  851. * Get the attachment path relative to the upload directory.
  852. *
  853. * @since 4.4.1
  854. * @access private
  855. *
  856. * @param string $file Attachment file name.
  857. * @return string Attachment path relative to the upload directory.
  858. */
  859. function _wp_get_attachment_relative_path( $file ) {
  860. $dirname = dirname( $file );
  861. if ( '.' === $dirname ) {
  862. return '';
  863. }
  864. if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
  865. // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
  866. $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
  867. $dirname = ltrim( $dirname, '/' );
  868. }
  869. return $dirname;
  870. }
  871. /**
  872. * Get the image size as array from its meta data.
  873. *
  874. * Used for responsive images.
  875. *
  876. * @since 4.4.0
  877. * @access private
  878. *
  879. * @param string $size_name Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
  880. * @param array $image_meta The image meta data.
  881. * @return array|bool Array of width and height values in pixels (in that order)
  882. * or false if the size doesn't exist.
  883. */
  884. function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
  885. if ( $size_name === 'full' ) {
  886. return array(
  887. absint( $image_meta['width'] ),
  888. absint( $image_meta['height'] ),
  889. );
  890. } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
  891. return array(
  892. absint( $image_meta['sizes'][$size_name]['width'] ),
  893. absint( $image_meta['sizes'][$size_name]['height'] ),
  894. );
  895. }
  896. return false;
  897. }
  898. /**
  899. * Retrieves the value for an image attachment's 'srcset' attribute.
  900. *
  901. * @since 4.4.0
  902. *
  903. * @see wp_calculate_image_srcset()
  904. *
  905. * @param int $attachment_id Image attachment ID.
  906. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of
  907. * width and height values in pixels (in that order). Default 'medium'.
  908. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  909. * Default null.
  910. * @return string|bool A 'srcset' value string or false.
  911. */
  912. function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
  913. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  914. return false;
  915. }
  916. if ( ! is_array( $image_meta ) ) {
  917. $image_meta = wp_get_attachment_metadata( $attachment_id );
  918. }
  919. $image_src = $image[0];
  920. $size_array = array(
  921. absint( $image[1] ),
  922. absint( $image[2] )
  923. );
  924. return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  925. }
  926. /**
  927. * A helper function to calculate the image sources to include in a 'srcset' attribute.
  928. *
  929. * @since 4.4.0
  930. *
  931. * @param array $size_array Array of width and height values in pixels (in that order).
  932. * @param string $image_src The 'src' of the image.
  933. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  934. * @param int $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
  935. * @return string|bool The 'srcset' attribute value. False on error or when only one source exists.
  936. */
  937. function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
  938. /**
  939. * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
  940. *
  941. * @since 4.5.0
  942. *
  943. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  944. * @param array $size_array Array of width and height values in pixels (in that order).
  945. * @param string $image_src The 'src' of the image.
  946. * @param int $attachment_id The image attachment ID or 0 if not supplied.
  947. */
  948. $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
  949. if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
  950. return false;
  951. }
  952. $image_sizes = $image_meta['sizes'];
  953. // Get the width and height of the image.
  954. $image_width = (int) $size_array[0];
  955. $image_height = (int) $size_array[1];
  956. // Bail early if error/no width.
  957. if ( $image_width < 1 ) {
  958. return false;
  959. }
  960. $image_basename = wp_basename( $image_meta['file'] );
  961. /*
  962. * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
  963. * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
  964. * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
  965. */
  966. if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
  967. $image_sizes[] = array(
  968. 'width' => $image_meta['width'],
  969. 'height' => $image_meta['height'],
  970. 'file' => $image_basename,
  971. );
  972. } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
  973. return false;
  974. }
  975. // Retrieve the uploads sub-directory from the full size image.
  976. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
  977. if ( $dirname ) {
  978. $dirname = trailingslashit( $dirname );
  979. }
  980. $upload_dir = wp_get_upload_dir();
  981. $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
  982. /*
  983. * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
  984. * (which is to say, when they share the domain name of the current request).
  985. */
  986. if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
  987. $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
  988. }
  989. /*
  990. * Images that have been edited in WordPress after being uploaded will
  991. * contain a unique hash. Look for that hash and use it later to filter
  992. * out images that are leftovers from previous versions.
  993. */
  994. $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
  995. /**
  996. * Filters the maximum image width to be included in a 'srcset' attribute.
  997. *
  998. * @since 4.4.0
  999. *
  1000. * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
  1001. * @param array $size_array Array of width and height values in pixels (in that order).
  1002. */
  1003. $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
  1004. // Array to hold URL candidates.
  1005. $sources = array();
  1006. /**
  1007. * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
  1008. * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
  1009. * an incorrect image. See #35045.
  1010. */
  1011. $src_matched = false;
  1012. /*
  1013. * Loop through available images. Only use images that are resized
  1014. * versions of the same edit.
  1015. */
  1016. foreach ( $image_sizes as $image ) {
  1017. $is_src = false;
  1018. // Check if image meta isn't corrupted.
  1019. if ( ! is_array( $image ) ) {
  1020. continue;
  1021. }
  1022. // If the file name is part of the `src`, we've confirmed a match.
  1023. if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
  1024. $src_matched = $is_src = true;
  1025. }
  1026. // Filter out images that are from previous edits.
  1027. if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
  1028. continue;
  1029. }
  1030. /*
  1031. * Filters out images that are wider than '$max_srcset_image_width' unless
  1032. * that file is in the 'src' attribute.
  1033. */
  1034. if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
  1035. continue;
  1036. }
  1037. // If the image dimensions are within 1px of the expected size, use it.
  1038. if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
  1039. // Add the URL, descriptor, and value to the sources array to be returned.
  1040. $source = array(
  1041. 'url' => $image_baseurl . $image['file'],
  1042. 'descriptor' => 'w',
  1043. 'value' => $image['width'],
  1044. );
  1045. // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
  1046. if ( $is_src ) {
  1047. $sources = array( $image['width'] => $source ) + $sources;
  1048. } else {
  1049. $sources[ $image['width'] ] = $source;
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Filters an image's 'srcset' sources.
  1055. *
  1056. * @since 4.4.0
  1057. *
  1058. * @param array $sources {
  1059. * One or more arrays of source data to include in the 'srcset'.
  1060. *
  1061. * @type array $width {
  1062. * @type string $url The URL of an image source.
  1063. * @type string $descriptor The descriptor type used in the image candidate string,
  1064. * either 'w' or 'x'.
  1065. * @type int $value The source width if paired with a 'w' descriptor, or a
  1066. * pixel density value if paired with an 'x' descriptor.
  1067. * }
  1068. * }
  1069. * @param array $size_array Array of width and height values in pixels (in that order).
  1070. * @param string $image_src The 'src' of the image.
  1071. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1072. * @param int $attachment_id Image attachment ID or 0.
  1073. */
  1074. $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
  1075. // Only return a 'srcset' value if there is more than one source.
  1076. if ( ! $src_matched || count( $sources ) < 2 ) {
  1077. return false;
  1078. }
  1079. $srcset = '';
  1080. foreach ( $sources as $source ) {
  1081. $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
  1082. }
  1083. return rtrim( $srcset, ', ' );
  1084. }
  1085. /**
  1086. * Retrieves the value for an image attachment's 'sizes' attribute.
  1087. *
  1088. * @since 4.4.0
  1089. *
  1090. * @see wp_calculate_image_sizes()
  1091. *
  1092. * @param int $attachment_id Image attachment ID.
  1093. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of width
  1094. * and height values in pixels (in that order). Default 'medium'.
  1095. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1096. * Default null.
  1097. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1098. */
  1099. function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
  1100. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  1101. return false;
  1102. }
  1103. if ( ! is_array( $image_meta ) ) {
  1104. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1105. }
  1106. $image_src = $image[0];
  1107. $size_array = array(
  1108. absint( $image[1] ),
  1109. absint( $image[2] )
  1110. );
  1111. return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1112. }
  1113. /**
  1114. * Creates a 'sizes' attribute value for an image.
  1115. *
  1116. * @since 4.4.0
  1117. *
  1118. * @param array|string $size Image size to retrieve. Accepts any valid image size, or an array
  1119. * of width and height values in pixels (in that order). Default 'medium'.
  1120. * @param string $image_src Optional. The URL to the image file. Default null.
  1121. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1122. * Default null.
  1123. * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
  1124. * is needed when using the image size name as argument for `$size`. Default 0.
  1125. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1126. */
  1127. function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
  1128. $width = 0;
  1129. if ( is_array( $size ) ) {
  1130. $width = absint( $size[0] );
  1131. } elseif ( is_string( $size ) ) {
  1132. if ( ! $image_meta && $attachment_id ) {
  1133. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1134. }
  1135. if ( is_array( $image_meta ) ) {
  1136. $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
  1137. if ( $size_array ) {
  1138. $width = absint( $size_array[0] );
  1139. }
  1140. }
  1141. }
  1142. if ( ! $width ) {
  1143. return false;
  1144. }
  1145. // Setup the default 'sizes' attribute.
  1146. $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
  1147. /**
  1148. * Filters the output of 'wp_calculate_image_sizes()'.
  1149. *
  1150. * @since 4.4.0
  1151. *
  1152. * @param string $sizes A source size value for use in a 'sizes' attribute.
  1153. * @param array|string $size Requested size. Image size or array of width and height values
  1154. * in pixels (in that order).
  1155. * @param string|null $image_src The URL to the image file or null.
  1156. * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
  1157. * @param int $attachment_id Image attachment ID of the original image or 0.
  1158. */
  1159. return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
  1160. }
  1161. /**
  1162. * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
  1163. *
  1164. * @since 4.4.0
  1165. *
  1166. * @see wp_image_add_srcset_and_sizes()
  1167. *
  1168. * @param string $content The raw post content to be filtered.
  1169. * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
  1170. */
  1171. function wp_make_content_images_responsive( $content ) {
  1172. if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
  1173. return $content;
  1174. }
  1175. $selected_images = $attachment_ids = array();
  1176. foreach( $matches[0] as $image ) {
  1177. if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
  1178. ( $attachment_id = absint( $class_id[1] ) ) ) {
  1179. /*
  1180. * If exactly the same image tag is used more than once, overwrite it.
  1181. * All identical tags will be replaced later with 'str_replace()'.
  1182. */
  1183. $selected_images[ $image ] = $attachment_id;
  1184. // Overwrite the ID when the same image is included more than once.
  1185. $attachment_ids[ $attachment_id ] = true;
  1186. }
  1187. }
  1188. if ( count( $attachment_ids ) > 1 ) {
  1189. /*
  1190. * Warm object cache for use with 'get_post_meta()'.
  1191. *
  1192. * To avoid making a database call for each image, a single query
  1193. * warms the object cache with the meta information for all images.
  1194. */
  1195. update_meta_cache( 'post', array_keys( $attachment_ids ) );
  1196. }
  1197. foreach ( $selected_images as $image => $attachment_id ) {
  1198. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1199. $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
  1200. }
  1201. return $content;
  1202. }
  1203. /**
  1204. * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
  1205. *
  1206. * @since 4.4.0
  1207. *
  1208. * @see wp_calculate_image_srcset()
  1209. * @see wp_calculate_image_sizes()
  1210. *
  1211. * @param string $image An HTML 'img' element to be filtered.
  1212. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1213. * @param int $attachment_id Image attachment ID.
  1214. * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
  1215. */
  1216. function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
  1217. // Ensure the image meta exists.
  1218. if ( empty( $image_meta['sizes'] ) ) {
  1219. return $image;
  1220. }
  1221. $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
  1222. list( $image_src ) = explode( '?', $image_src );
  1223. // Return early if we couldn't get the image source.
  1224. if ( ! $image_src ) {
  1225. return $image;
  1226. }
  1227. // Bail early if an image has been inserted and later edited.
  1228. if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
  1229. strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
  1230. return $image;
  1231. }
  1232. $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
  1233. $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
  1234. if ( ! $width || ! $height ) {
  1235. /*
  1236. * If attempts to parse the size value failed, attempt to use the image meta data to match
  1237. * the image file name from 'src' against the available sizes for an attachment.
  1238. */
  1239. $image_filename = wp_basename( $image_src );
  1240. if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
  1241. $width = (int) $image_meta['width'];
  1242. $height = (int) $image_meta['height'];
  1243. } else {
  1244. foreach( $image_meta['sizes'] as $image_size_data ) {
  1245. if ( $image_filename === $image_size_data['file'] ) {
  1246. $width = (int) $image_size_data['width'];
  1247. $height = (int) $image_size_data['height'];
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. }
  1253. if ( ! $width || ! $height ) {
  1254. return $image;
  1255. }
  1256. $size_array = array( $width, $height );
  1257. $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  1258. if ( $srcset ) {
  1259. // Check if there is already a 'sizes' attribute.
  1260. $sizes = strpos( $image, ' sizes=' );
  1261. if ( ! $sizes ) {
  1262. $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1263. }
  1264. }
  1265. if ( $srcset && $sizes ) {
  1266. // Format the 'srcset' and 'sizes' string and escape attributes.
  1267. $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
  1268. if ( is_string( $sizes ) ) {
  1269. $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
  1270. }
  1271. // Add 'srcset' and 'sizes' attributes to the image markup.
  1272. $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
  1273. }
  1274. return $image;
  1275. }
  1276. /**
  1277. * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
  1278. *
  1279. * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
  1280. * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
  1281. *
  1282. * @ignore
  1283. * @since 2.9.0
  1284. *
  1285. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1286. * @return array Modified array of attributes including the new 'wp-post-image' class.
  1287. */
  1288. function _wp_post_thumbnail_class_filter( $attr ) {
  1289. $attr['class'] .= ' wp-post-image';
  1290. return $attr;
  1291. }
  1292. /**
  1293. * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
  1294. * filter hook. Internal use only.
  1295. *
  1296. * @ignore
  1297. * @since 2.9.0
  1298. *
  1299. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1300. */
  1301. function _wp_post_thumbnail_class_filter_add( $attr ) {
  1302. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1303. }
  1304. /**
  1305. * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
  1306. * filter hook. Internal use only.
  1307. *
  1308. * @ignore
  1309. * @since 2.9.0
  1310. *
  1311. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1312. */
  1313. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  1314. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1315. }
  1316. add_shortcode('wp_caption', 'img_caption_shortcode');
  1317. add_shortcode('caption', 'img_caption_shortcode');
  1318. /**
  1319. * Builds the Caption shortcode output.
  1320. *
  1321. * Allows a plugin to replace the content that would otherwise be returned. The
  1322. * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
  1323. * parameter and the content parameter values.
  1324. *
  1325. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  1326. * 'caption'.
  1327. *
  1328. * @since 2.6.0
  1329. *
  1330. * @param array $attr {
  1331. * Attributes of the caption shortcode.
  1332. *
  1333. * @type string $id ID of the div element for the caption.
  1334. * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
  1335. * 'aligncenter', alignright', 'alignnone'.
  1336. * @type int $width The width of the caption, in pixels.
  1337. * @type string $caption The caption text.
  1338. * @type string $class Additional class name(s) added to the caption container.
  1339. * }
  1340. * @param string $content Shortcode content.
  1341. * @return string HTML content to display the caption.
  1342. */
  1343. function img_caption_shortcode( $attr, $content = null ) {
  1344. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  1345. if ( ! isset( $attr['caption'] ) ) {
  1346. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  1347. $content = $matches[1];
  1348. $attr['caption'] = trim( $matches[2] );
  1349. }
  1350. } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
  1351. $attr['caption'] = wp_kses( $attr['caption'], 'post' );
  1352. }
  1353. /**
  1354. * Filters the default caption shortcode output.
  1355. *
  1356. * If the filtered output isn't empty, it will be used instead of generating
  1357. * the default caption template.
  1358. *
  1359. * @since 2.6.0
  1360. *
  1361. * @see img_caption_shortcode()
  1362. *
  1363. * @param string $output The caption output. Default empty.
  1364. * @param array $attr Attributes of the caption shortcode.
  1365. * @param string $content The image element, possibly wrapped in a hyperlink.
  1366. */
  1367. $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
  1368. if ( $output != '' )
  1369. return $output;
  1370. $atts = shortcode_atts( array(
  1371. 'id' => '',
  1372. 'align' => 'alignnone',
  1373. 'width' => '',
  1374. 'caption' => '',
  1375. 'class' => '',
  1376. ), $attr, 'caption' );
  1377. $atts['width'] = (int) $atts['width'];
  1378. if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
  1379. return $content;
  1380. if ( ! empty( $atts['id'] ) )
  1381. $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
  1382. $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
  1383. $html5 = current_theme_supports( 'html5', 'caption' );
  1384. // HTML5 captions never added the extra 10px to the image width
  1385. $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
  1386. /**
  1387. * Filters the width of an image's caption.
  1388. *
  1389. * By default, the caption is 10 pixels greater than the width of the image,
  1390. * to prevent post content from running up against a floated image.
  1391. *
  1392. * @since 3.7.0
  1393. *
  1394. * @see img_caption_shortcode()
  1395. *
  1396. * @param int $width Width of the caption in pixels. To remove this inline style,
  1397. * return zero.
  1398. * @param array $atts Attributes of the caption shortcode.
  1399. * @param string $content The image element, possibly wrapped in a hyperlink.
  1400. */
  1401. $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
  1402. $style = '';
  1403. if ( $caption_width ) {
  1404. $style = 'style="width: ' . (int) $caption_width . 'px" ';
  1405. }
  1406. if ( $html5 ) {
  1407. $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
  1408. . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
  1409. } else {
  1410. $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
  1411. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
  1412. }
  1413. return $html;
  1414. }
  1415. add_shortcode('gallery', 'gallery_shortcode');
  1416. /**
  1417. * Builds the Gallery shortcode output.
  1418. *
  1419. * This implements the functionality of the Gallery Shortcode for displaying
  1420. * WordPress images on a post.
  1421. *
  1422. * @since 2.5.0
  1423. *
  1424. * @staticvar int $instance
  1425. *
  1426. * @param array $attr {
  1427. * Attributes of the gallery shortcode.
  1428. *
  1429. * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
  1430. * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
  1431. * Accepts any valid SQL ORDERBY statement.
  1432. * @type int $id Post ID.
  1433. * @type string $itemtag HTML tag to use for each image in the gallery.
  1434. * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
  1435. * @type string $icontag HTML tag to use for each image's icon.
  1436. * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
  1437. * @type string $captiontag HTML tag to use for each image's caption.
  1438. * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
  1439. * @type int $columns Number of columns of images to display. Default 3.
  1440. * @type string|array $size Size of the images to display. Accepts any valid image size, or an array of width
  1441. * and height values in pixels (in that order). Default 'thumbnail'.
  1442. * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
  1443. * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
  1444. * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
  1445. * @type string $link What to link each image to. Default empty (links to the attachment page).
  1446. * Accepts 'file', 'none'.
  1447. * }
  1448. * @return string HTML content to display gallery.
  1449. */
  1450. function gallery_shortcode( $attr ) {
  1451. $post = get_post();
  1452. static $instance = 0;
  1453. $instance++;
  1454. if ( ! empty( $attr['ids'] ) ) {
  1455. // 'ids' is explicitly ordered, unless you specify otherwise.
  1456. if ( empty( $attr['orderby'] ) ) {
  1457. $attr['orderby'] = 'post__in';
  1458. }
  1459. $attr['include'] = $attr['ids'];
  1460. }
  1461. /**
  1462. * Filters the default gallery shortcode output.
  1463. *
  1464. * If the filtered output isn't empty, it will be used instead of generating
  1465. * the default gallery template.
  1466. *
  1467. * @since 2.5.0
  1468. * @since 4.2.0 The `$instance` parameter was added.
  1469. *
  1470. * @see gallery_shortcode()
  1471. *
  1472. * @param string $output The gallery output. Default empty.
  1473. * @param array $attr Attributes of the gallery shortcode.
  1474. * @param int $instance Unique numeric ID of this gallery shortcode instance.
  1475. */
  1476. $output = apply_filters( 'post_gallery', '', $attr, $instance );
  1477. if ( $output != '' ) {
  1478. return $output;
  1479. }
  1480. $html5 = current_theme_supports( 'html5', 'gallery' );
  1481. $atts = shortcode_atts( array(
  1482. 'order' => 'ASC',
  1483. 'orderby' => 'menu_order ID',
  1484. 'id' => $post ? $post->ID : 0,
  1485. 'itemtag' => $html5 ? 'figure' : 'dl',
  1486. 'icontag' => $html5 ? 'div' : 'dt',
  1487. 'captiontag' => $html5 ? 'figcaption' : 'dd',
  1488. 'columns' => 3,
  1489. 'size' => 'thumbnail',
  1490. 'include' => '',
  1491. 'exclude' => '',
  1492. 'link' => ''
  1493. ), $attr, 'gallery' );
  1494. $id = intval( $atts['id'] );
  1495. if ( ! empty( $atts['include'] ) ) {
  1496. $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1497. $attachments = array();
  1498. foreach ( $_attachments as $key => $val ) {
  1499. $attachments[$val->ID] = $_attachments[$key];
  1500. }
  1501. } elseif ( ! empty( $atts['exclude'] ) ) {
  1502. $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1503. } else {
  1504. $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1505. }
  1506. if ( empty( $attachments ) ) {
  1507. return '';
  1508. }
  1509. if ( is_feed() ) {
  1510. $output = "\n";
  1511. foreach ( $attachments as $att_id => $attachment ) {
  1512. $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
  1513. }
  1514. return $output;
  1515. }
  1516. $itemtag = tag_escape( $atts['itemtag'] );
  1517. $captiontag = tag_escape( $atts['captiontag'] );
  1518. $icontag = tag_escape( $atts['icontag'] );
  1519. $valid_tags = wp_kses_allowed_html( 'post' );
  1520. if ( ! isset( $valid_tags[ $itemtag ] ) ) {
  1521. $itemtag = 'dl';
  1522. }
  1523. if ( ! isset( $valid_tags[ $captiontag ] ) ) {
  1524. $captiontag = 'dd';
  1525. }
  1526. if ( ! isset( $valid_tags[ $icontag ] ) ) {
  1527. $icontag = 'dt';
  1528. }
  1529. $columns = intval( $atts['columns'] );
  1530. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  1531. $float = is_rtl() ? 'right' : 'left';
  1532. $selector = "gallery-{$instance}";
  1533. $gallery_style = '';
  1534. /**
  1535. * Filters whether to print default gallery styles.
  1536. *
  1537. * @since 3.1.0
  1538. *
  1539. * @param bool $print Whether to print default gallery styles.
  1540. * Defaults to false if the theme supports HTML5 galleries.
  1541. * Otherwise, defaults to true.
  1542. */
  1543. if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
  1544. $gallery_style = "
  1545. <style type='text/css'>
  1546. #{$selector} {
  1547. margin: auto;
  1548. }
  1549. #{$selector} .gallery-item {
  1550. float: {$float};
  1551. margin-top: 10px;
  1552. text-align: center;
  1553. width: {$itemwidth}%;
  1554. }
  1555. #{$selector} img {
  1556. border: 2px solid #cfcfcf;
  1557. }
  1558. #{$selector} .gallery-caption {
  1559. margin-left: 0;
  1560. }
  1561. /* see gallery_shortcode() in wp-includes/media.php */
  1562. </style>\n\t\t";
  1563. }
  1564. $size_class = sanitize_html_class( $atts['size'] );
  1565. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  1566. /**
  1567. * Filters the default gallery shortcode CSS styles.
  1568. *
  1569. * @since 2.5.0
  1570. *
  1571. * @param string $gallery_style Default CSS styles and opening HTML div container
  1572. * for the gallery shortcode output.
  1573. */
  1574. $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
  1575. $i = 0;
  1576. foreach ( $attachments as $id => $attachment ) {
  1577. $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
  1578. if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
  1579. $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
  1580. } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
  1581. $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
  1582. } else {
  1583. $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
  1584. }
  1585. $image_meta = wp_get_attachment_metadata( $id );
  1586. $orientation = '';
  1587. if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
  1588. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  1589. }
  1590. $output .= "<{$itemtag} class='gallery-item'>";
  1591. $output .= "
  1592. <{$icontag} class='gallery-icon {$orientation}'>
  1593. $image_output
  1594. </{$icontag}>";
  1595. if ( $captiontag && trim($attachment->post_excerpt) ) {
  1596. $output .= "
  1597. <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
  1598. " . wptexturize($attachment->post_excerpt) . "
  1599. </{$captiontag}>";
  1600. }
  1601. $output .= "</{$itemtag}>";
  1602. if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
  1603. $output .= '<br style="clear: both" />';
  1604. }
  1605. }
  1606. if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
  1607. $output .= "
  1608. <br style='clear: both' />";
  1609. }
  1610. $output .= "
  1611. </div>\n";
  1612. return $output;
  1613. }
  1614. /**
  1615. * Outputs the templates used by playlists.
  1616. *
  1617. * @since 3.9.0
  1618. */
  1619. function wp_underscore_playlist_templates() {
  1620. ?>
  1621. <script type="text/html" id="tmpl-wp-playlist-current-item">
  1622. <# if ( data.image ) { #>
  1623. <img src="{{ data.thumb.src }}" alt="" />
  1624. <# } #>
  1625. <div class="wp-playlist-caption">
  1626. <span class="wp-playlist-item-meta wp-playlist-item-title"><?php
  1627. /* translators: playlist item title */
  1628. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
  1629. ?></span>
  1630. <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
  1631. <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
  1632. </div>
  1633. </script>
  1634. <script type="text/html" id="tmpl-wp-playlist-item">
  1635. <div class="wp-playlist-item">
  1636. <a class="wp-playlist-caption" href="{{ data.src }}">
  1637. {{ data.index ? ( data.index + '. ' ) : '' }}
  1638. <# if ( data.caption ) { #>
  1639. {{ data.caption }}
  1640. <# } else { #>
  1641. <span class="wp-playlist-item-title"><?php
  1642. /* translators: playlist item title */
  1643. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
  1644. ?></span>
  1645. <# if ( data.artists && data.meta.artist ) { #>
  1646. <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
  1647. <# } #>
  1648. <# } #>
  1649. </a>
  1650. <# if ( data.meta.length_formatted ) { #>
  1651. <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
  1652. <# } #>
  1653. </div>
  1654. </script>
  1655. <?php
  1656. }
  1657. /**
  1658. * Outputs and enqueue default scripts and styles for playlists.
  1659. *
  1660. * @since 3.9.0
  1661. *
  1662. * @param string $type Type of playlist. Accepts 'audio' or 'video'.
  1663. */
  1664. function wp_playlist_scripts( $type ) {
  1665. wp_enqueue_style( 'wp-mediaelement' );
  1666. wp_enqueue_script( 'wp-playlist' );
  1667. ?>
  1668. <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
  1669. <?php
  1670. add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
  1671. add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
  1672. }
  1673. /**
  1674. * Builds the Playlist shortcode output.
  1675. *
  1676. * This implements the functionality of the playlist shortcode for displaying
  1677. * a collection of WordPress audio or video files in a post.
  1678. *
  1679. * @since 3.9.0
  1680. *
  1681. * @global int $content_width
  1682. * @staticvar int $instance
  1683. *
  1684. * @param array $attr {
  1685. * Array of default playlist attributes.
  1686. *
  1687. * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
  1688. * @type string $order Designates ascending or descending order of items in the playlist.
  1689. * Accepts 'ASC', 'DESC'. Default 'ASC'.
  1690. * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
  1691. * passed, this defaults to the order of the $ids array ('post__in').
  1692. * Otherwise default is 'menu_order ID'.
  1693. * @type int $id If an explicit $ids array is not present, this parameter
  1694. * will determine which attachments are used for the playlist.
  1695. * Default is the current post ID.
  1696. * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
  1697. * a playlist will be created from all $type attachments of $id.
  1698. * Default empty.
  1699. * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
  1700. * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
  1701. * @type bool $tracklist Whether to show or hide the playlist. Default true.
  1702. * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
  1703. * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
  1704. * thumbnail). Default true.
  1705. * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
  1706. * }
  1707. *
  1708. * @return string Playlist output. Empty string if the passed type is unsupported.
  1709. */
  1710. function wp_playlist_shortcode( $attr ) {
  1711. global $content_width;
  1712. $post = get_post();
  1713. static $instance = 0;
  1714. $instance++;
  1715. if ( ! empty( $attr['ids'] ) ) {
  1716. // 'ids' is explicitly ordered, unless you specify otherwise.
  1717. if ( empty( $attr['orderby'] ) ) {
  1718. $attr['orderby'] = 'post__in';
  1719. }
  1720. $attr['include'] = $attr['ids'];
  1721. }
  1722. /**
  1723. * Filters the playlist output.
  1724. *
  1725. * Passing a non-empty value to the filter will short-circuit generation
  1726. * of the default playlist output, returning the passed value instead.
  1727. *
  1728. * @since 3.9.0
  1729. * @since 4.2.0 The `$instance` parameter was added.
  1730. *
  1731. * @param string $output Playlist output. Default empty.
  1732. * @param array $attr An array of shortcode attributes.
  1733. * @param int $instance Unique numeric ID of this playlist shortcode instance.
  1734. */
  1735. $output = apply_filters( 'post_playlist', '', $attr, $instance );
  1736. if ( $output != '' ) {
  1737. return $output;
  1738. }
  1739. $atts = shortcode_atts( array(
  1740. 'type' => 'audio',
  1741. 'order' => 'ASC',
  1742. 'orderby' => 'menu_order ID',
  1743. 'id' => $post ? $post->ID : 0,
  1744. 'include' => '',
  1745. 'exclude' => '',
  1746. 'style' => 'light',
  1747. 'tracklist' => true,
  1748. 'tracknumbers' => true,
  1749. 'images' => true,
  1750. 'artists' => true
  1751. ), $attr, 'playlist' );
  1752. $id = intval( $atts['id'] );
  1753. if ( $atts['type'] !== 'audio' ) {
  1754. $atts['type'] = 'video';
  1755. }
  1756. $args = array(
  1757. 'post_status' => 'inherit',
  1758. 'post_type' => 'attachment',
  1759. 'post_mime_type' => $atts['type'],
  1760. 'order' => $atts['order'],
  1761. 'orderby' => $atts['orderby']
  1762. );
  1763. if ( ! empty( $atts['include'] ) ) {
  1764. $args['include'] = $atts['include'];
  1765. $_attachments = get_posts( $args );
  1766. $attachments = array();
  1767. foreach ( $_attachments as $key => $val ) {
  1768. $attachments[$val->ID] = $_attachments[$key];
  1769. }
  1770. } elseif ( ! empty( $atts['exclude'] ) ) {
  1771. $args['post_parent'] = $id;
  1772. $args['exclude'] = $atts['exclude'];
  1773. $attachments = get_children( $args );
  1774. } else {
  1775. $args['post_parent'] = $id;
  1776. $attachments = get_children( $args );
  1777. }
  1778. if ( empty( $attachments ) ) {
  1779. return '';
  1780. }
  1781. if ( is_feed() ) {
  1782. $output = "\n";
  1783. foreach ( $attachments as $att_id => $attachment ) {
  1784. $output .= wp_get_attachment_link( $att_id ) . "\n";
  1785. }
  1786. return $output;
  1787. }
  1788. $outer = 22; // default padding and border of wrapper
  1789. $default_width = 640;
  1790. $default_height = 360;
  1791. $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
  1792. $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
  1793. $data = array(
  1794. 'type' => $atts['type'],
  1795. // don't pass strings to JSON, will be truthy in JS
  1796. 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
  1797. 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
  1798. 'images' => wp_validate_boolean( $atts['images'] ),
  1799. 'artists' => wp_validate_boolean( $atts['artists'] ),
  1800. );
  1801. $tracks = array();
  1802. foreach ( $attachments as $attachment ) {
  1803. $url = wp_get_attachment_url( $attachment->ID );
  1804. $ftype = wp_check_filetype( $url, wp_get_mime_types() );
  1805. $track = array(
  1806. 'src' => $url,
  1807. 'type' => $ftype['type'],
  1808. 'title' => $attachment->post_title,
  1809. 'caption' => $attachment->post_excerpt,
  1810. 'description' => $attachment->post_content
  1811. );
  1812. $track['meta'] = array();
  1813. $meta = wp_get_attachment_metadata( $attachment->ID );
  1814. if ( ! empty( $meta ) ) {
  1815. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  1816. if ( ! empty( $meta[ $key ] ) ) {
  1817. $track['meta'][ $key ] = $meta[ $key ];
  1818. }
  1819. }
  1820. if ( 'video' === $atts['type'] ) {
  1821. if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
  1822. $width = $meta['width'];
  1823. $height = $meta['height'];
  1824. $theme_height = round( ( $height * $theme_width ) / $width );
  1825. } else {
  1826. $width = $default_width;
  1827. $height = $default_height;
  1828. }
  1829. $track['dimensions'] = array(
  1830. 'original' => compact( 'width', 'height' ),
  1831. 'resized' => array(
  1832. 'width' => $theme_width,
  1833. 'height' => $theme_height
  1834. )
  1835. );
  1836. }
  1837. }
  1838. if ( $atts['images'] ) {
  1839. $thumb_id = get_post_thumbnail_id( $attachment->ID );
  1840. if ( ! empty( $thumb_id ) ) {
  1841. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
  1842. $track['image'] = compact( 'src', 'width', 'height' );
  1843. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
  1844. $track['thumb'] = compact( 'src', 'width', 'height' );
  1845. } else {
  1846. $src = wp_mime_type_icon( $attachment->ID );
  1847. $width = 48;
  1848. $height = 64;
  1849. $track['image'] = compact( 'src', 'width', 'height' );
  1850. $track['thumb'] = compact( 'src', 'width', 'height' );
  1851. }
  1852. }
  1853. $tracks[] = $track;
  1854. }
  1855. $data['tracks'] = $tracks;
  1856. $safe_type = esc_attr( $atts['type'] );
  1857. $safe_style = esc_attr( $atts['style'] );
  1858. ob_start();
  1859. if ( 1 === $instance ) {
  1860. /**
  1861. * Prints and enqueues playlist scripts, styles, and JavaScript templates.
  1862. *
  1863. * @since 3.9.0
  1864. *
  1865. * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
  1866. * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
  1867. */
  1868. do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
  1869. } ?>
  1870. <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
  1871. <?php if ( 'audio' === $atts['type'] ): ?>
  1872. <div class="wp-playlist-current-item"></div>
  1873. <?php endif ?>
  1874. <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
  1875. echo (int) $theme_width;
  1876. ?>"<?php if ( 'video' === $safe_type ):
  1877. echo ' height="', (int) $theme_height, '"';
  1878. endif; ?>></<?php echo $safe_type ?>>
  1879. <div class="wp-playlist-next"></div>
  1880. <div class="wp-playlist-prev"></div>
  1881. <noscript>
  1882. <ol><?php
  1883. foreach ( $attachments as $att_id => $attachment ) {
  1884. printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
  1885. }
  1886. ?></ol>
  1887. </noscript>
  1888. <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
  1889. </div>
  1890. <?php
  1891. return ob_get_clean();
  1892. }
  1893. add_shortcode( 'playlist', 'wp_playlist_shortcode' );
  1894. /**
  1895. * Provides a No-JS Flash fallback as a last resort for audio / video.
  1896. *
  1897. * @since 3.6.0
  1898. *
  1899. * @param string $url The media element URL.
  1900. * @return string Fallback HTML.
  1901. */
  1902. function wp_mediaelement_fallback( $url ) {
  1903. /**
  1904. * Filters the Mediaelement fallback output for no-JS.
  1905. *
  1906. * @since 3.6.0
  1907. *
  1908. * @param string $output Fallback output for no-JS.
  1909. * @param string $url Media file URL.
  1910. */
  1911. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  1912. }
  1913. /**
  1914. * Returns a filtered list of WP-supported audio formats.
  1915. *
  1916. * @since 3.6.0
  1917. *
  1918. * @return array Supported audio formats.
  1919. */
  1920. function wp_get_audio_extensions() {
  1921. /**
  1922. * Filters the list of supported audio formats.
  1923. *
  1924. * @since 3.6.0
  1925. *
  1926. * @param array $extensions An array of support audio formats. Defaults are
  1927. * 'mp3', 'ogg', 'm4a', 'wav'.
  1928. */
  1929. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'm4a', 'wav' ) );
  1930. }
  1931. /**
  1932. * Returns useful keys to use to lookup data from an attachment's stored metadata.
  1933. *
  1934. * @since 3.9.0
  1935. *
  1936. * @param WP_Post $attachment The current attachment, provided for context.
  1937. * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
  1938. * @return array Key/value pairs of field keys to labels.
  1939. */
  1940. function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
  1941. $fields = array(
  1942. 'artist' => __( 'Artist' ),
  1943. 'album' => __( 'Album' ),
  1944. );
  1945. if ( 'display' === $context ) {
  1946. $fields['genre'] = __( 'Genre' );
  1947. $fields['year'] = __( 'Year' );
  1948. $fields['length_formatted'] = _x( 'Length', 'video or audio' );
  1949. } elseif ( 'js' === $context ) {
  1950. $fields['bitrate'] = __( 'Bitrate' );
  1951. $fields['bitrate_mode'] = __( 'Bitrate Mode' );
  1952. }
  1953. /**
  1954. * Filters the editable list of keys to look up data from an attachment's metadata.
  1955. *
  1956. * @since 3.9.0
  1957. *
  1958. * @param array $fields Key/value pairs of field keys to labels.
  1959. * @param WP_Post $attachment Attachment object.
  1960. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  1961. */
  1962. return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
  1963. }
  1964. /**
  1965. * Builds the Audio shortcode output.
  1966. *
  1967. * This implements the functionality of the Audio Shortcode for displaying
  1968. * WordPress mp3s in a post.
  1969. *
  1970. * @since 3.6.0
  1971. *
  1972. * @staticvar int $instance
  1973. *
  1974. * @param array $attr {
  1975. * Attributes of the audio shortcode.
  1976. *
  1977. * @type string $src URL to the source of the audio file. Default empty.
  1978. * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
  1979. * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
  1980. * @type string $preload The 'preload' attribute for the `<audio>` element. Default 'none'.
  1981. * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
  1982. * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
  1983. * }
  1984. * @param string $content Shortcode content.
  1985. * @return string|void HTML content to display audio.
  1986. */
  1987. function wp_audio_shortcode( $attr, $content = '' ) {
  1988. $post_id = get_post() ? get_the_ID() : 0;
  1989. static $instance = 0;
  1990. $instance++;
  1991. /**
  1992. * Filters the default audio shortcode output.
  1993. *
  1994. * If the filtered output isn't empty, it will be used instead of generating the default audio template.
  1995. *
  1996. * @since 3.6.0
  1997. *
  1998. * @param string $html Empty variable to be replaced with shortcode markup.
  1999. * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
  2000. * @param string $content Shortcode content.
  2001. * @param int $instance Unique numeric ID of this audio shortcode instance.
  2002. */
  2003. $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
  2004. if ( '' !== $override ) {
  2005. return $override;
  2006. }
  2007. $audio = null;
  2008. $default_types = wp_get_audio_extensions();
  2009. $defaults_atts = array(
  2010. 'src' => '',
  2011. 'loop' => '',
  2012. 'autoplay' => '',
  2013. 'preload' => 'none',
  2014. 'class' => 'wp-audio-shortcode',
  2015. 'style' => 'width: 100%;'
  2016. );
  2017. foreach ( $default_types as $type ) {
  2018. $defaults_atts[$type] = '';
  2019. }
  2020. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  2021. $primary = false;
  2022. if ( ! empty( $atts['src'] ) ) {
  2023. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2024. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  2025. return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2026. }
  2027. $primary = true;
  2028. array_unshift( $default_types, 'src' );
  2029. } else {
  2030. foreach ( $default_types as $ext ) {
  2031. if ( ! empty( $atts[ $ext ] ) ) {
  2032. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2033. if ( strtolower( $type['ext'] ) === $ext ) {
  2034. $primary = true;
  2035. }
  2036. }
  2037. }
  2038. }
  2039. if ( ! $primary ) {
  2040. $audios = get_attached_media( 'audio', $post_id );
  2041. if ( empty( $audios ) ) {
  2042. return;
  2043. }
  2044. $audio = reset( $audios );
  2045. $atts['src'] = wp_get_attachment_url( $audio->ID );
  2046. if ( empty( $atts['src'] ) ) {
  2047. return;
  2048. }
  2049. array_unshift( $default_types, 'src' );
  2050. }
  2051. /**
  2052. * Filters the media library used for the audio shortcode.
  2053. *
  2054. * @since 3.6.0
  2055. *
  2056. * @param string $library Media library used for the audio shortcode.
  2057. */
  2058. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  2059. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2060. wp_enqueue_style( 'wp-mediaelement' );
  2061. wp_enqueue_script( 'wp-mediaelement' );
  2062. }
  2063. /**
  2064. * Filters the class attribute for the audio shortcode output container.
  2065. *
  2066. * @since 3.6.0
  2067. *
  2068. * @param string $class CSS class or list of space-separated classes.
  2069. */
  2070. $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'] );
  2071. $html_atts = array(
  2072. 'class' => $atts['class'],
  2073. 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
  2074. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2075. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2076. 'preload' => $atts['preload'],
  2077. 'style' => $atts['style'],
  2078. );
  2079. // These ones should just be omitted altogether if they are blank
  2080. foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  2081. if ( empty( $html_atts[$a] ) ) {
  2082. unset( $html_atts[$a] );
  2083. }
  2084. }
  2085. $attr_strings = array();
  2086. foreach ( $html_atts as $k => $v ) {
  2087. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2088. }
  2089. $html = '';
  2090. if ( 'mediaelement' === $library && 1 === $instance ) {
  2091. $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  2092. }
  2093. $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
  2094. $fileurl = '';
  2095. $source = '<source type="%s" src="%s" />';
  2096. foreach ( $default_types as $fallback ) {
  2097. if ( ! empty( $atts[ $fallback ] ) ) {
  2098. if ( empty( $fileurl ) ) {
  2099. $fileurl = $atts[ $fallback ];
  2100. }
  2101. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2102. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2103. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2104. }
  2105. }
  2106. if ( 'mediaelement' === $library ) {
  2107. $html .= wp_mediaelement_fallback( $fileurl );
  2108. }
  2109. $html .= '</audio>';
  2110. /**
  2111. * Filters the audio shortcode output.
  2112. *
  2113. * @since 3.6.0
  2114. *
  2115. * @param string $html Audio shortcode HTML output.
  2116. * @param array $atts Array of audio shortcode attributes.
  2117. * @param string $audio Audio file.
  2118. * @param int $post_id Post ID.
  2119. * @param string $library Media library used for the audio shortcode.
  2120. */
  2121. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  2122. }
  2123. add_shortcode( 'audio', 'wp_audio_shortcode' );
  2124. /**
  2125. * Returns a filtered list of WP-supported video formats.
  2126. *
  2127. * @since 3.6.0
  2128. *
  2129. * @return array List of supported video formats.
  2130. */
  2131. function wp_get_video_extensions() {
  2132. /**
  2133. * Filters the list of supported video formats.
  2134. *
  2135. * @since 3.6.0
  2136. *
  2137. * @param array $extensions An array of support video formats. Defaults are
  2138. * 'mp4', 'm4v', 'webm', 'ogv', 'flv'.
  2139. */
  2140. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
  2141. }
  2142. /**
  2143. * Builds the Video shortcode output.
  2144. *
  2145. * This implements the functionality of the Video Shortcode for displaying
  2146. * WordPress mp4s in a post.
  2147. *
  2148. * @since 3.6.0
  2149. *
  2150. * @global int $content_width
  2151. * @staticvar int $instance
  2152. *
  2153. * @param array $attr {
  2154. * Attributes of the shortcode.
  2155. *
  2156. * @type string $src URL to the source of the video file. Default empty.
  2157. * @type int $height Height of the video embed in pixels. Default 360.
  2158. * @type int $width Width of the video embed in pixels. Default $content_width or 640.
  2159. * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
  2160. * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
  2161. * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
  2162. * @type string $preload The 'preload' attribute for the `<video>` element.
  2163. * Default 'metadata'.
  2164. * @type string $class The 'class' attribute for the `<video>` element.
  2165. * Default 'wp-video-shortcode'.
  2166. * }
  2167. * @param string $content Shortcode content.
  2168. * @return string|void HTML content to display video.
  2169. */
  2170. function wp_video_shortcode( $attr, $content = '' ) {
  2171. global $content_width;
  2172. $post_id = get_post() ? get_the_ID() : 0;
  2173. static $instance = 0;
  2174. $instance++;
  2175. /**
  2176. * Filters the default video shortcode output.
  2177. *
  2178. * If the filtered output isn't empty, it will be used instead of generating
  2179. * the default video template.
  2180. *
  2181. * @since 3.6.0
  2182. *
  2183. * @see wp_video_shortcode()
  2184. *
  2185. * @param string $html Empty variable to be replaced with shortcode markup.
  2186. * @param array $attr Attributes of the video shortcode.
  2187. * @param string $content Video shortcode content.
  2188. * @param int $instance Unique numeric ID of this video shortcode instance.
  2189. */
  2190. $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
  2191. if ( '' !== $override ) {
  2192. return $override;
  2193. }
  2194. $video = null;
  2195. $default_types = wp_get_video_extensions();
  2196. $defaults_atts = array(
  2197. 'src' => '',
  2198. 'poster' => '',
  2199. 'loop' => '',
  2200. 'autoplay' => '',
  2201. 'preload' => 'metadata',
  2202. 'width' => 640,
  2203. 'height' => 360,
  2204. 'class' => 'wp-video-shortcode',
  2205. );
  2206. foreach ( $default_types as $type ) {
  2207. $defaults_atts[$type] = '';
  2208. }
  2209. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  2210. if ( is_admin() ) {
  2211. // shrink the video so it isn't huge in the admin
  2212. if ( $atts['width'] > $defaults_atts['width'] ) {
  2213. $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
  2214. $atts['width'] = $defaults_atts['width'];
  2215. }
  2216. } else {
  2217. // if the video is bigger than the theme
  2218. if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
  2219. $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
  2220. $atts['width'] = $content_width;
  2221. }
  2222. }
  2223. $is_vimeo = $is_youtube = false;
  2224. $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
  2225. $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
  2226. $primary = false;
  2227. if ( ! empty( $atts['src'] ) ) {
  2228. $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
  2229. $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
  2230. if ( ! $is_youtube && ! $is_vimeo ) {
  2231. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2232. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  2233. return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2234. }
  2235. }
  2236. if ( $is_vimeo ) {
  2237. wp_enqueue_script( 'froogaloop' );
  2238. }
  2239. $primary = true;
  2240. array_unshift( $default_types, 'src' );
  2241. } else {
  2242. foreach ( $default_types as $ext ) {
  2243. if ( ! empty( $atts[ $ext ] ) ) {
  2244. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2245. if ( strtolower( $type['ext'] ) === $ext ) {
  2246. $primary = true;
  2247. }
  2248. }
  2249. }
  2250. }
  2251. if ( ! $primary ) {
  2252. $videos = get_attached_media( 'video', $post_id );
  2253. if ( empty( $videos ) ) {
  2254. return;
  2255. }
  2256. $video = reset( $videos );
  2257. $atts['src'] = wp_get_attachment_url( $video->ID );
  2258. if ( empty( $atts['src'] ) ) {
  2259. return;
  2260. }
  2261. array_unshift( $default_types, 'src' );
  2262. }
  2263. /**
  2264. * Filters the media library used for the video shortcode.
  2265. *
  2266. * @since 3.6.0
  2267. *
  2268. * @param string $library Media library used for the video shortcode.
  2269. */
  2270. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  2271. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2272. wp_enqueue_style( 'wp-mediaelement' );
  2273. wp_enqueue_script( 'wp-mediaelement' );
  2274. }
  2275. // Mediaelement has issues with some URL formats for Vimeo and YouTube, so
  2276. // update the URL to prevent the ME.js player from breaking.
  2277. if ( 'mediaelement' === $library ) {
  2278. if ( $is_youtube ) {
  2279. // Remove `feature` query arg and force SSL - see #40866.
  2280. $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
  2281. $atts['src'] = set_url_scheme( $atts['src'], 'https' );
  2282. } elseif ( $is_vimeo ) {
  2283. // Remove all query arguments and force SSL - see #40866.
  2284. $parsed_vimeo_url = wp_parse_url( $atts['src'] );
  2285. $vimeo_src = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
  2286. // Add loop param for mejs bug - see #40977, not needed after #39686.
  2287. $loop = $atts['loop'] ? '1' : '0';
  2288. $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
  2289. }
  2290. }
  2291. /**
  2292. * Filters the class attribute for the video shortcode output container.
  2293. *
  2294. * @since 3.6.0
  2295. *
  2296. * @param string $class CSS class or list of space-separated classes.
  2297. */
  2298. $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'] );
  2299. $html_atts = array(
  2300. 'class' => $atts['class'],
  2301. 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
  2302. 'width' => absint( $atts['width'] ),
  2303. 'height' => absint( $atts['height'] ),
  2304. 'poster' => esc_url( $atts['poster'] ),
  2305. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2306. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2307. 'preload' => $atts['preload'],
  2308. );
  2309. // These ones should just be omitted altogether if they are blank
  2310. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  2311. if ( empty( $html_atts[$a] ) ) {
  2312. unset( $html_atts[$a] );
  2313. }
  2314. }
  2315. $attr_strings = array();
  2316. foreach ( $html_atts as $k => $v ) {
  2317. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2318. }
  2319. $html = '';
  2320. if ( 'mediaelement' === $library && 1 === $instance ) {
  2321. $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  2322. }
  2323. $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  2324. $fileurl = '';
  2325. $source = '<source type="%s" src="%s" />';
  2326. foreach ( $default_types as $fallback ) {
  2327. if ( ! empty( $atts[ $fallback ] ) ) {
  2328. if ( empty( $fileurl ) ) {
  2329. $fileurl = $atts[ $fallback ];
  2330. }
  2331. if ( 'src' === $fallback && $is_youtube ) {
  2332. $type = array( 'type' => 'video/youtube' );
  2333. } elseif ( 'src' === $fallback && $is_vimeo ) {
  2334. $type = array( 'type' => 'video/vimeo' );
  2335. } else {
  2336. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2337. }
  2338. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2339. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2340. }
  2341. }
  2342. if ( ! empty( $content ) ) {
  2343. if ( false !== strpos( $content, "\n" ) ) {
  2344. $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
  2345. }
  2346. $html .= trim( $content );
  2347. }
  2348. if ( 'mediaelement' === $library ) {
  2349. $html .= wp_mediaelement_fallback( $fileurl );
  2350. }
  2351. $html .= '</video>';
  2352. $width_rule = '';
  2353. if ( ! empty( $atts['width'] ) ) {
  2354. $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
  2355. }
  2356. $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
  2357. /**
  2358. * Filters the output of the video shortcode.
  2359. *
  2360. * @since 3.6.0
  2361. *
  2362. * @param string $output Video shortcode HTML output.
  2363. * @param array $atts Array of video shortcode attributes.
  2364. * @param string $video Video file.
  2365. * @param int $post_id Post ID.
  2366. * @param string $library Media library used for the video shortcode.
  2367. */
  2368. return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
  2369. }
  2370. add_shortcode( 'video', 'wp_video_shortcode' );
  2371. /**
  2372. * Displays previous image link that has the same post parent.
  2373. *
  2374. * @since 2.5.0
  2375. *
  2376. * @see adjacent_image_link()
  2377. *
  2378. * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
  2379. * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
  2380. * default to 'post_title' or `$text`. Default 'thumbnail'.
  2381. * @param string $text Optional. Link text. Default false.
  2382. */
  2383. function previous_image_link( $size = 'thumbnail', $text = false ) {
  2384. adjacent_image_link(true, $size, $text);
  2385. }
  2386. /**
  2387. * Displays next image link that has the same post parent.
  2388. *
  2389. * @since 2.5.0
  2390. *
  2391. * @see adjacent_image_link()
  2392. *
  2393. * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
  2394. * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
  2395. * default to 'post_title' or `$text`. Default 'thumbnail'.
  2396. * @param string $text Optional. Link text. Default false.
  2397. */
  2398. function next_image_link( $size = 'thumbnail', $text = false ) {
  2399. adjacent_image_link(false, $size, $text);
  2400. }
  2401. /**
  2402. * Displays next or previous image link that has the same post parent.
  2403. *
  2404. * Retrieves the current attachment object from the $post global.
  2405. *
  2406. * @since 2.5.0
  2407. *
  2408. * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
  2409. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
  2410. * values in pixels (in that order). Default 'thumbnail'.
  2411. * @param bool $text Optional. Link text. Default false.
  2412. */
  2413. function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
  2414. $post = get_post();
  2415. $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' ) ) );
  2416. foreach ( $attachments as $k => $attachment ) {
  2417. if ( $attachment->ID == $post->ID ) {
  2418. break;
  2419. }
  2420. }
  2421. $output = '';
  2422. $attachment_id = 0;
  2423. if ( $attachments ) {
  2424. $k = $prev ? $k - 1 : $k + 1;
  2425. if ( isset( $attachments[ $k ] ) ) {
  2426. $attachment_id = $attachments[ $k ]->ID;
  2427. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  2428. }
  2429. }
  2430. $adjacent = $prev ? 'previous' : 'next';
  2431. /**
  2432. * Filters the adjacent image link.
  2433. *
  2434. * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
  2435. * either 'next', or 'previous'.
  2436. *
  2437. * @since 3.5.0
  2438. *
  2439. * @param string $output Adjacent image HTML markup.
  2440. * @param int $attachment_id Attachment ID
  2441. * @param string $size Image size.
  2442. * @param string $text Link text.
  2443. */
  2444. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  2445. }
  2446. /**
  2447. * Retrieves taxonomies attached to given the attachment.
  2448. *
  2449. * @since 2.5.0
  2450. * @since 4.7.0 Introduced the `$output` parameter.
  2451. *
  2452. * @param int|array|object $attachment Attachment ID, data array, or data object.
  2453. * @param string $output Output type. 'names' to return an array of taxonomy names,
  2454. * or 'objects' to return an array of taxonomy objects.
  2455. * Default is 'names'.
  2456. * @return array Empty array on failure. List of taxonomies on success.
  2457. */
  2458. function get_attachment_taxonomies( $attachment, $output = 'names' ) {
  2459. if ( is_int( $attachment ) ) {
  2460. $attachment = get_post( $attachment );
  2461. } elseif ( is_array( $attachment ) ) {
  2462. $attachment = (object) $attachment;
  2463. }
  2464. if ( ! is_object($attachment) )
  2465. return array();
  2466. $file = get_attached_file( $attachment->ID );
  2467. $filename = basename( $file );
  2468. $objects = array('attachment');
  2469. if ( false !== strpos($filename, '.') )
  2470. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  2471. if ( !empty($attachment->post_mime_type) ) {
  2472. $objects[] = 'attachment:' . $attachment->post_mime_type;
  2473. if ( false !== strpos($attachment->post_mime_type, '/') )
  2474. foreach ( explode('/', $attachment->post_mime_type) as $token )
  2475. if ( !empty($token) )
  2476. $objects[] = "attachment:$token";
  2477. }
  2478. $taxonomies = array();
  2479. foreach ( $objects as $object ) {
  2480. if ( $taxes = get_object_taxonomies( $object, $output ) ) {
  2481. $taxonomies = array_merge( $taxonomies, $taxes );
  2482. }
  2483. }
  2484. if ( 'names' === $output ) {
  2485. $taxonomies = array_unique( $taxonomies );
  2486. }
  2487. return $taxonomies;
  2488. }
  2489. /**
  2490. * Retrieves all of the taxonomy names that are registered for attachments.
  2491. *
  2492. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  2493. *
  2494. * @since 3.5.0
  2495. *
  2496. * @see get_taxonomies()
  2497. *
  2498. * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
  2499. * Default 'names'.
  2500. * @return array The names of all taxonomy of $object_type.
  2501. */
  2502. function get_taxonomies_for_attachments( $output = 'names' ) {
  2503. $taxonomies = array();
  2504. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  2505. foreach ( $taxonomy->object_type as $object_type ) {
  2506. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  2507. if ( 'names' == $output )
  2508. $taxonomies[] = $taxonomy->name;
  2509. else
  2510. $taxonomies[ $taxonomy->name ] = $taxonomy;
  2511. break;
  2512. }
  2513. }
  2514. }
  2515. return $taxonomies;
  2516. }
  2517. /**
  2518. * Create new GD image resource with transparency support
  2519. *
  2520. * @todo: Deprecate if possible.
  2521. *
  2522. * @since 2.9.0
  2523. *
  2524. * @param int $width Image width in pixels.
  2525. * @param int $height Image height in pixels..
  2526. * @return resource The GD image resource.
  2527. */
  2528. function wp_imagecreatetruecolor($width, $height) {
  2529. $img = imagecreatetruecolor($width, $height);
  2530. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  2531. imagealphablending($img, false);
  2532. imagesavealpha($img, true);
  2533. }
  2534. return $img;
  2535. }
  2536. /**
  2537. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  2538. *
  2539. * @since 2.9.0
  2540. *
  2541. * @see wp_constrain_dimensions()
  2542. *
  2543. * @param int $example_width The width of an example embed.
  2544. * @param int $example_height The height of an example embed.
  2545. * @param int $max_width The maximum allowed width.
  2546. * @param int $max_height The maximum allowed height.
  2547. * @return array The maximum possible width and height based on the example ratio.
  2548. */
  2549. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  2550. $example_width = (int) $example_width;
  2551. $example_height = (int) $example_height;
  2552. $max_width = (int) $max_width;
  2553. $max_height = (int) $max_height;
  2554. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  2555. }
  2556. /**
  2557. * Determines the maximum upload size allowed in php.ini.
  2558. *
  2559. * @since 2.5.0
  2560. *
  2561. * @return int Allowed upload size.
  2562. */
  2563. function wp_max_upload_size() {
  2564. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  2565. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  2566. /**
  2567. * Filters the maximum upload size allowed in php.ini.
  2568. *
  2569. * @since 2.5.0
  2570. *
  2571. * @param int $size Max upload size limit in bytes.
  2572. * @param int $u_bytes Maximum upload filesize in bytes.
  2573. * @param int $p_bytes Maximum size of POST data in bytes.
  2574. */
  2575. return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  2576. }
  2577. /**
  2578. * Returns a WP_Image_Editor instance and loads file into it.
  2579. *
  2580. * @since 3.5.0
  2581. *
  2582. * @param string $path Path to the file to load.
  2583. * @param array $args Optional. Additional arguments for retrieving the image editor.
  2584. * Default empty array.
  2585. * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
  2586. * object otherwise.
  2587. */
  2588. function wp_get_image_editor( $path, $args = array() ) {
  2589. $args['path'] = $path;
  2590. if ( ! isset( $args['mime_type'] ) ) {
  2591. $file_info = wp_check_filetype( $args['path'] );
  2592. // If $file_info['type'] is false, then we let the editor attempt to
  2593. // figure out the file type, rather than forcing a failure based on extension.
  2594. if ( isset( $file_info ) && $file_info['type'] )
  2595. $args['mime_type'] = $file_info['type'];
  2596. }
  2597. $implementation = _wp_image_editor_choose( $args );
  2598. if ( $implementation ) {
  2599. $editor = new $implementation( $path );
  2600. $loaded = $editor->load();
  2601. if ( is_wp_error( $loaded ) )
  2602. return $loaded;
  2603. return $editor;
  2604. }
  2605. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  2606. }
  2607. /**
  2608. * Tests whether there is an editor that supports a given mime type or methods.
  2609. *
  2610. * @since 3.5.0
  2611. *
  2612. * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
  2613. * Default empty array.
  2614. * @return bool True if an eligible editor is found; false otherwise.
  2615. */
  2616. function wp_image_editor_supports( $args = array() ) {
  2617. return (bool) _wp_image_editor_choose( $args );
  2618. }
  2619. /**
  2620. * Tests which editors are capable of supporting the request.
  2621. *
  2622. * @ignore
  2623. * @since 3.5.0
  2624. *
  2625. * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
  2626. * @return string|false Class name for the first editor that claims to support the request. False if no
  2627. * editor claims to support the request.
  2628. */
  2629. function _wp_image_editor_choose( $args = array() ) {
  2630. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  2631. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  2632. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  2633. /**
  2634. * Filters the list of image editing library classes.
  2635. *
  2636. * @since 3.5.0
  2637. *
  2638. * @param array $image_editors List of available image editors. Defaults are
  2639. * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
  2640. */
  2641. $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  2642. foreach ( $implementations as $implementation ) {
  2643. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  2644. continue;
  2645. if ( isset( $args['mime_type'] ) &&
  2646. ! call_user_func(
  2647. array( $implementation, 'supports_mime_type' ),
  2648. $args['mime_type'] ) ) {
  2649. continue;
  2650. }
  2651. if ( isset( $args['methods'] ) &&
  2652. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  2653. continue;
  2654. }
  2655. return $implementation;
  2656. }
  2657. return false;
  2658. }
  2659. /**
  2660. * Prints default Plupload arguments.
  2661. *
  2662. * @since 3.4.0
  2663. */
  2664. function wp_plupload_default_settings() {
  2665. $wp_scripts = wp_scripts();
  2666. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  2667. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  2668. return;
  2669. $max_upload_size = wp_max_upload_size();
  2670. $allowed_extensions = array_keys( get_allowed_mime_types() );
  2671. $extensions = array();
  2672. foreach ( $allowed_extensions as $extension ) {
  2673. $extensions = array_merge( $extensions, explode( '|', $extension ) );
  2674. }
  2675. $defaults = array(
  2676. 'runtimes' => 'html5,flash,silverlight,html4',
  2677. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  2678. 'url' => admin_url( 'async-upload.php', 'relative' ),
  2679. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  2680. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  2681. 'filters' => array(
  2682. 'max_file_size' => $max_upload_size . 'b',
  2683. 'mime_types' => array( array( 'extensions' => implode( ',', $extensions ) ) ),
  2684. ),
  2685. );
  2686. // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
  2687. // when enabled. See #29602.
  2688. if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
  2689. strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
  2690. $defaults['multi_selection'] = false;
  2691. }
  2692. /**
  2693. * Filters the Plupload default settings.
  2694. *
  2695. * @since 3.4.0
  2696. *
  2697. * @param array $defaults Default Plupload settings array.
  2698. */
  2699. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  2700. $params = array(
  2701. 'action' => 'upload-attachment',
  2702. );
  2703. /**
  2704. * Filters the Plupload default parameters.
  2705. *
  2706. * @since 3.4.0
  2707. *
  2708. * @param array $params Default Plupload parameters array.
  2709. */
  2710. $params = apply_filters( 'plupload_default_params', $params );
  2711. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  2712. $defaults['multipart_params'] = $params;
  2713. $settings = array(
  2714. 'defaults' => $defaults,
  2715. 'browser' => array(
  2716. 'mobile' => wp_is_mobile(),
  2717. 'supported' => _device_can_upload(),
  2718. ),
  2719. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  2720. );
  2721. $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
  2722. if ( $data )
  2723. $script = "$data\n$script";
  2724. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  2725. }
  2726. /**
  2727. * Prepares an attachment post object for JS, where it is expected
  2728. * to be JSON-encoded and fit into an Attachment model.
  2729. *
  2730. * @since 3.5.0
  2731. *
  2732. * @param mixed $attachment Attachment ID or object.
  2733. * @return array|void Array of attachment details.
  2734. */
  2735. function wp_prepare_attachment_for_js( $attachment ) {
  2736. if ( ! $attachment = get_post( $attachment ) )
  2737. return;
  2738. if ( 'attachment' != $attachment->post_type )
  2739. return;
  2740. $meta = wp_get_attachment_metadata( $attachment->ID );
  2741. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  2742. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  2743. else
  2744. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  2745. $attachment_url = wp_get_attachment_url( $attachment->ID );
  2746. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  2747. $response = array(
  2748. 'id' => $attachment->ID,
  2749. 'title' => $attachment->post_title,
  2750. 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
  2751. 'url' => $attachment_url,
  2752. 'link' => get_attachment_link( $attachment->ID ),
  2753. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  2754. 'author' => $attachment->post_author,
  2755. 'description' => $attachment->post_content,
  2756. 'caption' => $attachment->post_excerpt,
  2757. 'name' => $attachment->post_name,
  2758. 'status' => $attachment->post_status,
  2759. 'uploadedTo' => $attachment->post_parent,
  2760. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  2761. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  2762. 'menuOrder' => $attachment->menu_order,
  2763. 'mime' => $attachment->post_mime_type,
  2764. 'type' => $type,
  2765. 'subtype' => $subtype,
  2766. 'icon' => wp_mime_type_icon( $attachment->ID ),
  2767. 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
  2768. 'nonces' => array(
  2769. 'update' => false,
  2770. 'delete' => false,
  2771. 'edit' => false
  2772. ),
  2773. 'editLink' => false,
  2774. 'meta' => false,
  2775. );
  2776. $author = new WP_User( $attachment->post_author );
  2777. if ( $author->exists() ) {
  2778. $response['authorName'] = html_entity_decode( $author->display_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
  2779. } else {
  2780. $response['authorName'] = __( '(no author)' );
  2781. }
  2782. if ( $attachment->post_parent ) {
  2783. $post_parent = get_post( $attachment->post_parent );
  2784. } else {
  2785. $post_parent = false;
  2786. }
  2787. if ( $post_parent ) {
  2788. $parent_type = get_post_type_object( $post_parent->post_type );
  2789. if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
  2790. $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
  2791. }
  2792. if ( $parent_type && current_user_can( 'read_post', $attachment->post_parent ) ) {
  2793. $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
  2794. }
  2795. }
  2796. $attached_file = get_attached_file( $attachment->ID );
  2797. if ( isset( $meta['filesize'] ) ) {
  2798. $bytes = $meta['filesize'];
  2799. } elseif ( file_exists( $attached_file ) ) {
  2800. $bytes = filesize( $attached_file );
  2801. } else {
  2802. $bytes = '';
  2803. }
  2804. if ( $bytes ) {
  2805. $response['filesizeInBytes'] = $bytes;
  2806. $response['filesizeHumanReadable'] = size_format( $bytes );
  2807. }
  2808. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  2809. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  2810. $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  2811. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  2812. }
  2813. if ( current_user_can( 'delete_post', $attachment->ID ) )
  2814. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  2815. if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
  2816. $sizes = array();
  2817. /** This filter is documented in wp-admin/includes/media.php */
  2818. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  2819. 'thumbnail' => __('Thumbnail'),
  2820. 'medium' => __('Medium'),
  2821. 'large' => __('Large'),
  2822. 'full' => __('Full Size'),
  2823. ) );
  2824. unset( $possible_sizes['full'] );
  2825. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  2826. // First: run the image_downsize filter. If it returns something, we can use its data.
  2827. // If the filter does not return something, then image_downsize() is just an expensive
  2828. // way to check the image metadata, which we do second.
  2829. foreach ( $possible_sizes as $size => $label ) {
  2830. /** This filter is documented in wp-includes/media.php */
  2831. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  2832. if ( empty( $downsize[3] ) ) {
  2833. continue;
  2834. }
  2835. $sizes[ $size ] = array(
  2836. 'height' => $downsize[2],
  2837. 'width' => $downsize[1],
  2838. 'url' => $downsize[0],
  2839. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  2840. );
  2841. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  2842. // Nothing from the filter, so consult image metadata if we have it.
  2843. $size_meta = $meta['sizes'][ $size ];
  2844. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  2845. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  2846. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  2847. $sizes[ $size ] = array(
  2848. 'height' => $height,
  2849. 'width' => $width,
  2850. 'url' => $base_url . $size_meta['file'],
  2851. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  2852. );
  2853. }
  2854. }
  2855. if ( 'image' === $type ) {
  2856. $sizes['full'] = array( 'url' => $attachment_url );
  2857. if ( isset( $meta['height'], $meta['width'] ) ) {
  2858. $sizes['full']['height'] = $meta['height'];
  2859. $sizes['full']['width'] = $meta['width'];
  2860. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  2861. }
  2862. $response = array_merge( $response, $sizes['full'] );
  2863. } elseif ( $meta['sizes']['full']['file'] ) {
  2864. $sizes['full'] = array(
  2865. 'url' => $base_url . $meta['sizes']['full']['file'],
  2866. 'height' => $meta['sizes']['full']['height'],
  2867. 'width' => $meta['sizes']['full']['width'],
  2868. 'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape'
  2869. );
  2870. }
  2871. $response = array_merge( $response, array( 'sizes' => $sizes ) );
  2872. }
  2873. if ( $meta && 'video' === $type ) {
  2874. if ( isset( $meta['width'] ) )
  2875. $response['width'] = (int) $meta['width'];
  2876. if ( isset( $meta['height'] ) )
  2877. $response['height'] = (int) $meta['height'];
  2878. }
  2879. if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  2880. if ( isset( $meta['length_formatted'] ) )
  2881. $response['fileLength'] = $meta['length_formatted'];
  2882. $response['meta'] = array();
  2883. foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
  2884. $response['meta'][ $key ] = false;
  2885. if ( ! empty( $meta[ $key ] ) ) {
  2886. $response['meta'][ $key ] = $meta[ $key ];
  2887. }
  2888. }
  2889. $id = get_post_thumbnail_id( $attachment->ID );
  2890. if ( ! empty( $id ) ) {
  2891. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  2892. $response['image'] = compact( 'src', 'width', 'height' );
  2893. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  2894. $response['thumb'] = compact( 'src', 'width', 'height' );
  2895. } else {
  2896. $src = wp_mime_type_icon( $attachment->ID );
  2897. $width = 48;
  2898. $height = 64;
  2899. $response['image'] = compact( 'src', 'width', 'height' );
  2900. $response['thumb'] = compact( 'src', 'width', 'height' );
  2901. }
  2902. }
  2903. if ( function_exists('get_compat_media_markup') )
  2904. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  2905. /**
  2906. * Filters the attachment data prepared for JavaScript.
  2907. *
  2908. * @since 3.5.0
  2909. *
  2910. * @param array $response Array of prepared attachment data.
  2911. * @param int|object $attachment Attachment ID or object.
  2912. * @param array $meta Array of attachment meta data.
  2913. */
  2914. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  2915. }
  2916. /**
  2917. * Enqueues all scripts, styles, settings, and templates necessary to use
  2918. * all media JS APIs.
  2919. *
  2920. * @since 3.5.0
  2921. *
  2922. * @global int $content_width
  2923. * @global wpdb $wpdb
  2924. * @global WP_Locale $wp_locale
  2925. *
  2926. * @param array $args {
  2927. * Arguments for enqueuing media scripts.
  2928. *
  2929. * @type int|WP_Post A post object or ID.
  2930. * }
  2931. */
  2932. function wp_enqueue_media( $args = array() ) {
  2933. // Enqueue me just once per page, please.
  2934. if ( did_action( 'wp_enqueue_media' ) )
  2935. return;
  2936. global $content_width, $wpdb, $wp_locale;
  2937. $defaults = array(
  2938. 'post' => null,
  2939. );
  2940. $args = wp_parse_args( $args, $defaults );
  2941. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  2942. // to ensure plugins will work. We will then unset those tabs.
  2943. $tabs = array(
  2944. // handler action suffix => tab label
  2945. 'type' => '',
  2946. 'type_url' => '',
  2947. 'gallery' => '',
  2948. 'library' => '',
  2949. );
  2950. /** This filter is documented in wp-admin/includes/media.php */
  2951. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  2952. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  2953. $props = array(
  2954. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  2955. 'align' => get_option( 'image_default_align' ), // empty default
  2956. 'size' => get_option( 'image_default_size' ), // empty default
  2957. );
  2958. $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
  2959. $mimes = get_allowed_mime_types();
  2960. $ext_mimes = array();
  2961. foreach ( $exts as $ext ) {
  2962. foreach ( $mimes as $ext_preg => $mime_match ) {
  2963. if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
  2964. $ext_mimes[ $ext ] = $mime_match;
  2965. break;
  2966. }
  2967. }
  2968. }
  2969. /**
  2970. * Allows showing or hiding the "Create Audio Playlist" button in the media library.
  2971. *
  2972. * By default, the "Create Audio Playlist" button will always be shown in
  2973. * the media library. If this filter returns `null`, a query will be run
  2974. * to determine whether the media library contains any audio items. This
  2975. * was the default behavior prior to version 4.8.0, but this query is
  2976. * expensive for large media libraries.
  2977. *
  2978. * @since 4.7.4
  2979. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  2980. *
  2981. * @link https://core.trac.wordpress.org/ticket/31071
  2982. *
  2983. * @param bool|null Whether to show the button, or `null` to decide based
  2984. * on whether any audio files exist in the media library.
  2985. */
  2986. $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
  2987. if ( null === $show_audio_playlist ) {
  2988. $show_audio_playlist = $wpdb->get_var( "
  2989. SELECT ID
  2990. FROM $wpdb->posts
  2991. WHERE post_type = 'attachment'
  2992. AND post_mime_type LIKE 'audio%'
  2993. LIMIT 1
  2994. " );
  2995. }
  2996. /**
  2997. * Allows showing or hiding the "Create Video Playlist" button in the media library.
  2998. *
  2999. * By default, the "Create Video Playlist" button will always be shown in
  3000. * the media library. If this filter returns `null`, a query will be run
  3001. * to determine whether the media library contains any video items. This
  3002. * was the default behavior prior to version 4.8.0, but this query is
  3003. * expensive for large media libraries.
  3004. *
  3005. * @since 4.7.4
  3006. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  3007. *
  3008. * @link https://core.trac.wordpress.org/ticket/31071
  3009. *
  3010. * @param bool|null Whether to show the button, or `null` to decide based
  3011. * on whether any video files exist in the media library.
  3012. */
  3013. $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
  3014. if ( null === $show_video_playlist ) {
  3015. $show_video_playlist = $wpdb->get_var( "
  3016. SELECT ID
  3017. FROM $wpdb->posts
  3018. WHERE post_type = 'attachment'
  3019. AND post_mime_type LIKE 'video%'
  3020. LIMIT 1
  3021. " );
  3022. }
  3023. /**
  3024. * Allows overriding the list of months displayed in the media library.
  3025. *
  3026. * By default (if this filter does not return an array), a query will be
  3027. * run to determine the months that have media items. This query can be
  3028. * expensive for large media libraries, so it may be desirable for sites to
  3029. * override this behavior.
  3030. *
  3031. * @since 4.7.4
  3032. *
  3033. * @link https://core.trac.wordpress.org/ticket/31071
  3034. *
  3035. * @param array|null An array of objects with `month` and `year`
  3036. * properties, or `null` (or any other non-array value)
  3037. * for default behavior.
  3038. */
  3039. $months = apply_filters( 'media_library_months_with_files', null );
  3040. if ( ! is_array( $months ) ) {
  3041. $months = $wpdb->get_results( $wpdb->prepare( "
  3042. SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
  3043. FROM $wpdb->posts
  3044. WHERE post_type = %s
  3045. ORDER BY post_date DESC
  3046. ", 'attachment' ) );
  3047. }
  3048. foreach ( $months as $month_year ) {
  3049. $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
  3050. }
  3051. $settings = array(
  3052. 'tabs' => $tabs,
  3053. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  3054. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  3055. /** This filter is documented in wp-admin/includes/media.php */
  3056. 'captions' => ! apply_filters( 'disable_captions', '' ),
  3057. 'nonce' => array(
  3058. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  3059. 'wpRestApi' => wp_create_nonce( 'wp_rest' ),
  3060. ),
  3061. 'post' => array(
  3062. 'id' => 0,
  3063. ),
  3064. 'defaultProps' => $props,
  3065. 'attachmentCounts' => array(
  3066. 'audio' => ( $show_audio_playlist ) ? 1 : 0,
  3067. 'video' => ( $show_video_playlist ) ? 1 : 0,
  3068. ),
  3069. 'oEmbedProxyUrl' => rest_url( 'oembed/1.0/proxy' ),
  3070. 'embedExts' => $exts,
  3071. 'embedMimes' => $ext_mimes,
  3072. 'contentWidth' => $content_width,
  3073. 'months' => $months,
  3074. 'mediaTrash' => MEDIA_TRASH ? 1 : 0,
  3075. );
  3076. $post = null;
  3077. if ( isset( $args['post'] ) ) {
  3078. $post = get_post( $args['post'] );
  3079. $settings['post'] = array(
  3080. 'id' => $post->ID,
  3081. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  3082. );
  3083. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
  3084. if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
  3085. if ( wp_attachment_is( 'audio', $post ) ) {
  3086. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  3087. } elseif ( wp_attachment_is( 'video', $post ) ) {
  3088. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  3089. }
  3090. }
  3091. if ( $thumbnail_support ) {
  3092. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  3093. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  3094. }
  3095. }
  3096. if ( $post ) {
  3097. $post_type_object = get_post_type_object( $post->post_type );
  3098. } else {
  3099. $post_type_object = get_post_type_object( 'post' );
  3100. }
  3101. $strings = array(
  3102. // Generic
  3103. 'url' => __( 'URL' ),
  3104. 'addMedia' => __( 'Add Media' ),
  3105. 'search' => __( 'Search' ),
  3106. 'select' => __( 'Select' ),
  3107. 'cancel' => __( 'Cancel' ),
  3108. 'update' => __( 'Update' ),
  3109. 'replace' => __( 'Replace' ),
  3110. 'remove' => __( 'Remove' ),
  3111. 'back' => __( 'Back' ),
  3112. /* translators: This is a would-be plural string used in the media manager.
  3113. If there is not a word you can use in your language to avoid issues with the
  3114. lack of plural support here, turn it into "selected: %d" then translate it.
  3115. */
  3116. 'selected' => __( '%d selected' ),
  3117. 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
  3118. // Upload
  3119. 'uploadFilesTitle' => __( 'Upload Files' ),
  3120. 'uploadImagesTitle' => __( 'Upload Images' ),
  3121. // Library
  3122. 'mediaLibraryTitle' => __( 'Media Library' ),
  3123. 'insertMediaTitle' => __( 'Insert Media' ),
  3124. 'createNewGallery' => __( 'Create a new gallery' ),
  3125. 'createNewPlaylist' => __( 'Create a new playlist' ),
  3126. 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  3127. 'returnToLibrary' => __( '&#8592; Return to library' ),
  3128. 'allMediaItems' => __( 'All media items' ),
  3129. 'allDates' => __( 'All dates' ),
  3130. 'noItemsFound' => __( 'No items found.' ),
  3131. 'insertIntoPost' => $post_type_object->labels->insert_into_item,
  3132. 'unattached' => __( 'Unattached' ),
  3133. 'trash' => _x( 'Trash', 'noun' ),
  3134. 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item,
  3135. 'warnDelete' => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3136. 'warnBulkDelete' => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3137. 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
  3138. 'bulkSelect' => __( 'Bulk Select' ),
  3139. 'cancelSelection' => __( 'Cancel Selection' ),
  3140. 'trashSelected' => __( 'Trash Selected' ),
  3141. 'untrashSelected' => __( 'Untrash Selected' ),
  3142. 'deleteSelected' => __( 'Delete Selected' ),
  3143. 'deletePermanently' => __( 'Delete Permanently' ),
  3144. 'apply' => __( 'Apply' ),
  3145. 'filterByDate' => __( 'Filter by date' ),
  3146. 'filterByType' => __( 'Filter by type' ),
  3147. 'searchMediaLabel' => __( 'Search Media' ),
  3148. 'searchMediaPlaceholder' => __( 'Search media items...' ), // placeholder (no ellipsis)
  3149. 'noMedia' => __( 'No media files found.' ),
  3150. // Library Details
  3151. 'attachmentDetails' => __( 'Attachment Details' ),
  3152. // From URL
  3153. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  3154. // Featured Images
  3155. 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
  3156. 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
  3157. // Gallery
  3158. 'createGalleryTitle' => __( 'Create Gallery' ),
  3159. 'editGalleryTitle' => __( 'Edit Gallery' ),
  3160. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  3161. 'insertGallery' => __( 'Insert gallery' ),
  3162. 'updateGallery' => __( 'Update gallery' ),
  3163. 'addToGallery' => __( 'Add to gallery' ),
  3164. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  3165. 'reverseOrder' => __( 'Reverse order' ),
  3166. // Edit Image
  3167. 'imageDetailsTitle' => __( 'Image Details' ),
  3168. 'imageReplaceTitle' => __( 'Replace Image' ),
  3169. 'imageDetailsCancel' => __( 'Cancel Edit' ),
  3170. 'editImage' => __( 'Edit Image' ),
  3171. // Crop Image
  3172. 'chooseImage' => __( 'Choose Image' ),
  3173. 'selectAndCrop' => __( 'Select and Crop' ),
  3174. 'skipCropping' => __( 'Skip Cropping' ),
  3175. 'cropImage' => __( 'Crop Image' ),
  3176. 'cropYourImage' => __( 'Crop your image' ),
  3177. 'cropping' => __( 'Cropping&hellip;' ),
  3178. /* translators: 1: suggested width number, 2: suggested height number. */
  3179. 'suggestedDimensions' => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
  3180. 'cropError' => __( 'There has been an error cropping your image.' ),
  3181. // Edit Audio
  3182. 'audioDetailsTitle' => __( 'Audio Details' ),
  3183. 'audioReplaceTitle' => __( 'Replace Audio' ),
  3184. 'audioAddSourceTitle' => __( 'Add Audio Source' ),
  3185. 'audioDetailsCancel' => __( 'Cancel Edit' ),
  3186. // Edit Video
  3187. 'videoDetailsTitle' => __( 'Video Details' ),
  3188. 'videoReplaceTitle' => __( 'Replace Video' ),
  3189. 'videoAddSourceTitle' => __( 'Add Video Source' ),
  3190. 'videoDetailsCancel' => __( 'Cancel Edit' ),
  3191. 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
  3192. 'videoAddTrackTitle' => __( 'Add Subtitles' ),
  3193. // Playlist
  3194. 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
  3195. 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
  3196. 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
  3197. 'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
  3198. 'insertPlaylist' => __( 'Insert audio playlist' ),
  3199. 'updatePlaylist' => __( 'Update audio playlist' ),
  3200. 'addToPlaylist' => __( 'Add to audio playlist' ),
  3201. 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
  3202. // Video Playlist
  3203. 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
  3204. 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
  3205. 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
  3206. 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
  3207. 'insertVideoPlaylist' => __( 'Insert video playlist' ),
  3208. 'updateVideoPlaylist' => __( 'Update video playlist' ),
  3209. 'addToVideoPlaylist' => __( 'Add to video playlist' ),
  3210. 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
  3211. );
  3212. /**
  3213. * Filters the media view settings.
  3214. *
  3215. * @since 3.5.0
  3216. *
  3217. * @param array $settings List of media view settings.
  3218. * @param WP_Post $post Post object.
  3219. */
  3220. $settings = apply_filters( 'media_view_settings', $settings, $post );
  3221. /**
  3222. * Filters the media view strings.
  3223. *
  3224. * @since 3.5.0
  3225. *
  3226. * @param array $strings List of media view strings.
  3227. * @param WP_Post $post Post object.
  3228. */
  3229. $strings = apply_filters( 'media_view_strings', $strings, $post );
  3230. $strings['settings'] = $settings;
  3231. // Ensure we enqueue media-editor first, that way media-views is
  3232. // registered internally before we try to localize it. see #24724.
  3233. wp_enqueue_script( 'media-editor' );
  3234. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  3235. wp_enqueue_script( 'media-audiovideo' );
  3236. wp_enqueue_style( 'media-views' );
  3237. if ( is_admin() ) {
  3238. wp_enqueue_script( 'mce-view' );
  3239. wp_enqueue_script( 'image-edit' );
  3240. }
  3241. wp_enqueue_style( 'imgareaselect' );
  3242. wp_plupload_default_settings();
  3243. require_once ABSPATH . WPINC . '/media-template.php';
  3244. add_action( 'admin_footer', 'wp_print_media_templates' );
  3245. add_action( 'wp_footer', 'wp_print_media_templates' );
  3246. add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
  3247. /**
  3248. * Fires at the conclusion of wp_enqueue_media().
  3249. *
  3250. * @since 3.5.0
  3251. */
  3252. do_action( 'wp_enqueue_media' );
  3253. }
  3254. /**
  3255. * Retrieves media attached to the passed post.
  3256. *
  3257. * @since 3.6.0
  3258. *
  3259. * @param string $type Mime type.
  3260. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  3261. * @return array Found attachments.
  3262. */
  3263. function get_attached_media( $type, $post = 0 ) {
  3264. if ( ! $post = get_post( $post ) )
  3265. return array();
  3266. $args = array(
  3267. 'post_parent' => $post->ID,
  3268. 'post_type' => 'attachment',
  3269. 'post_mime_type' => $type,
  3270. 'posts_per_page' => -1,
  3271. 'orderby' => 'menu_order',
  3272. 'order' => 'ASC',
  3273. );
  3274. /**
  3275. * Filters arguments used to retrieve media attached to the given post.
  3276. *
  3277. * @since 3.6.0
  3278. *
  3279. * @param array $args Post query arguments.
  3280. * @param string $type Mime type of the desired media.
  3281. * @param mixed $post Post ID or object.
  3282. */
  3283. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  3284. $children = get_children( $args );
  3285. /**
  3286. * Filters the list of media attached to the given post.
  3287. *
  3288. * @since 3.6.0
  3289. *
  3290. * @param array $children Associative array of media attached to the given post.
  3291. * @param string $type Mime type of the media desired.
  3292. * @param mixed $post Post ID or object.
  3293. */
  3294. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  3295. }
  3296. /**
  3297. * Check the content blob for an audio, video, object, embed, or iframe tags.
  3298. *
  3299. * @since 3.6.0
  3300. *
  3301. * @param string $content A string which might contain media data.
  3302. * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
  3303. * @return array A list of found HTML media embeds.
  3304. */
  3305. function get_media_embedded_in_content( $content, $types = null ) {
  3306. $html = array();
  3307. /**
  3308. * Filters the embedded media types that are allowed to be returned from the content blob.
  3309. *
  3310. * @since 4.2.0
  3311. *
  3312. * @param array $allowed_media_types An array of allowed media types. Default media types are
  3313. * 'audio', 'video', 'object', 'embed', and 'iframe'.
  3314. */
  3315. $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
  3316. if ( ! empty( $types ) ) {
  3317. if ( ! is_array( $types ) ) {
  3318. $types = array( $types );
  3319. }
  3320. $allowed_media_types = array_intersect( $allowed_media_types, $types );
  3321. }
  3322. $tags = implode( '|', $allowed_media_types );
  3323. if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
  3324. foreach ( $matches[0] as $match ) {
  3325. $html[] = $match;
  3326. }
  3327. }
  3328. return $html;
  3329. }
  3330. /**
  3331. * Retrieves galleries from the passed post's content.
  3332. *
  3333. * @since 3.6.0
  3334. *
  3335. * @param int|WP_Post $post Post ID or object.
  3336. * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
  3337. * @return array A list of arrays, each containing gallery data and srcs parsed
  3338. * from the expanded shortcode.
  3339. */
  3340. function get_post_galleries( $post, $html = true ) {
  3341. if ( ! $post = get_post( $post ) )
  3342. return array();
  3343. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  3344. return array();
  3345. $galleries = array();
  3346. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  3347. foreach ( $matches as $shortcode ) {
  3348. if ( 'gallery' === $shortcode[2] ) {
  3349. $srcs = array();
  3350. $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
  3351. if ( ! is_array( $shortcode_attrs ) ) {
  3352. $shortcode_attrs = array();
  3353. }
  3354. // Specify the post id of the gallery we're viewing if the shortcode doesn't reference another post already.
  3355. if ( ! isset( $shortcode_attrs['id'] ) ) {
  3356. $shortcode[3] .= ' id="' . intval( $post->ID ) . '"';
  3357. }
  3358. $gallery = do_shortcode_tag( $shortcode );
  3359. if ( $html ) {
  3360. $galleries[] = $gallery;
  3361. } else {
  3362. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  3363. if ( ! empty( $src ) ) {
  3364. foreach ( $src as $s ) {
  3365. $srcs[] = $s[2];
  3366. }
  3367. }
  3368. $galleries[] = array_merge(
  3369. $shortcode_attrs,
  3370. array(
  3371. 'src' => array_values( array_unique( $srcs ) )
  3372. )
  3373. );
  3374. }
  3375. }
  3376. }
  3377. }
  3378. /**
  3379. * Filters the list of all found galleries in the given post.
  3380. *
  3381. * @since 3.6.0
  3382. *
  3383. * @param array $galleries Associative array of all found post galleries.
  3384. * @param WP_Post $post Post object.
  3385. */
  3386. return apply_filters( 'get_post_galleries', $galleries, $post );
  3387. }
  3388. /**
  3389. * Check a specified post's content for gallery and, if present, return the first
  3390. *
  3391. * @since 3.6.0
  3392. *
  3393. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  3394. * @param bool $html Optional. Whether to return HTML or data. Default is true.
  3395. * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  3396. */
  3397. function get_post_gallery( $post = 0, $html = true ) {
  3398. $galleries = get_post_galleries( $post, $html );
  3399. $gallery = reset( $galleries );
  3400. /**
  3401. * Filters the first-found post gallery.
  3402. *
  3403. * @since 3.6.0
  3404. *
  3405. * @param array $gallery The first-found post gallery.
  3406. * @param int|WP_Post $post Post ID or object.
  3407. * @param array $galleries Associative array of all found post galleries.
  3408. */
  3409. return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  3410. }
  3411. /**
  3412. * Retrieve the image srcs from galleries from a post's content, if present
  3413. *
  3414. * @since 3.6.0
  3415. *
  3416. * @see get_post_galleries()
  3417. *
  3418. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  3419. * @return array A list of lists, each containing image srcs parsed.
  3420. * from an expanded shortcode
  3421. */
  3422. function get_post_galleries_images( $post = 0 ) {
  3423. $galleries = get_post_galleries( $post, false );
  3424. return wp_list_pluck( $galleries, 'src' );
  3425. }
  3426. /**
  3427. * Checks a post's content for galleries and return the image srcs for the first found gallery
  3428. *
  3429. * @since 3.6.0
  3430. *
  3431. * @see get_post_gallery()
  3432. *
  3433. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  3434. * @return array A list of a gallery's image srcs in order.
  3435. */
  3436. function get_post_gallery_images( $post = 0 ) {
  3437. $gallery = get_post_gallery( $post, false );
  3438. return empty( $gallery['src'] ) ? array() : $gallery['src'];
  3439. }
  3440. /**
  3441. * Maybe attempts to generate attachment metadata, if missing.
  3442. *
  3443. * @since 3.9.0
  3444. *
  3445. * @param WP_Post $attachment Attachment object.
  3446. */
  3447. function wp_maybe_generate_attachment_metadata( $attachment ) {
  3448. if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
  3449. return;
  3450. }
  3451. $file = get_attached_file( $attachment_id );
  3452. $meta = wp_get_attachment_metadata( $attachment_id );
  3453. if ( empty( $meta ) && file_exists( $file ) ) {
  3454. $_meta = get_post_meta( $attachment_id );
  3455. $regeneration_lock = 'wp_generating_att_' . $attachment_id;
  3456. if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
  3457. set_transient( $regeneration_lock, $file );
  3458. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
  3459. delete_transient( $regeneration_lock );
  3460. }
  3461. }
  3462. }
  3463. /**
  3464. * Tries to convert an attachment URL into a post ID.
  3465. *
  3466. * @since 4.0.0
  3467. *
  3468. * @global wpdb $wpdb WordPress database abstraction object.
  3469. *
  3470. * @param string $url The URL to resolve.
  3471. * @return int The found post ID, or 0 on failure.
  3472. */
  3473. function attachment_url_to_postid( $url ) {
  3474. global $wpdb;
  3475. $dir = wp_get_upload_dir();
  3476. $path = $url;
  3477. $site_url = parse_url( $dir['url'] );
  3478. $image_path = parse_url( $path );
  3479. //force the protocols to match if needed
  3480. if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
  3481. $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
  3482. }
  3483. if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
  3484. $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
  3485. }
  3486. $sql = $wpdb->prepare(
  3487. "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
  3488. $path
  3489. );
  3490. $post_id = $wpdb->get_var( $sql );
  3491. /**
  3492. * Filters an attachment id found by URL.
  3493. *
  3494. * @since 4.2.0
  3495. *
  3496. * @param int|null $post_id The post_id (if any) found by the function.
  3497. * @param string $url The URL being looked up.
  3498. */
  3499. return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
  3500. }
  3501. /**
  3502. * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
  3503. *
  3504. * @since 4.0.0
  3505. *
  3506. * @return array The relevant CSS file URLs.
  3507. */
  3508. function wpview_media_sandbox_styles() {
  3509. $version = 'ver=' . get_bloginfo( 'version' );
  3510. $mediaelement = includes_url( "js/mediaelement/mediaelementplayer.min.css?$version" );
  3511. $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
  3512. return array( $mediaelement, $wpmediaelement );
  3513. }