暫無描述

media.php 174KB

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