Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

media.php 131 KiB

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