media.php 187 KB

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