media.php 145 KB

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