No Description

post.php 258KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850
  1. <?php
  2. /**
  3. * Core Post API
  4. *
  5. * @package WordPress
  6. * @subpackage Post
  7. */
  8. //
  9. // Post Type registration.
  10. //
  11. /**
  12. * Creates the initial post types when 'init' action is fired.
  13. *
  14. * See {@see 'init'}.
  15. *
  16. * @since 2.9.0
  17. */
  18. function create_initial_post_types() {
  19. register_post_type(
  20. 'post',
  21. array(
  22. 'labels' => array(
  23. 'name_admin_bar' => _x( 'Post', 'add new from admin bar' ),
  24. ),
  25. 'public' => true,
  26. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  27. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  28. 'capability_type' => 'post',
  29. 'map_meta_cap' => true,
  30. 'menu_position' => 5,
  31. 'menu_icon' => 'dashicons-admin-post',
  32. 'hierarchical' => false,
  33. 'rewrite' => false,
  34. 'query_var' => false,
  35. 'delete_with_user' => true,
  36. 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
  37. 'show_in_rest' => true,
  38. 'rest_base' => 'posts',
  39. 'rest_controller_class' => 'WP_REST_Posts_Controller',
  40. )
  41. );
  42. register_post_type(
  43. 'page',
  44. array(
  45. 'labels' => array(
  46. 'name_admin_bar' => _x( 'Page', 'add new from admin bar' ),
  47. ),
  48. 'public' => true,
  49. 'publicly_queryable' => false,
  50. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  51. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  52. 'capability_type' => 'page',
  53. 'map_meta_cap' => true,
  54. 'menu_position' => 20,
  55. 'menu_icon' => 'dashicons-admin-page',
  56. 'hierarchical' => true,
  57. 'rewrite' => false,
  58. 'query_var' => false,
  59. 'delete_with_user' => true,
  60. 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
  61. 'show_in_rest' => true,
  62. 'rest_base' => 'pages',
  63. 'rest_controller_class' => 'WP_REST_Posts_Controller',
  64. )
  65. );
  66. register_post_type(
  67. 'attachment',
  68. array(
  69. 'labels' => array(
  70. 'name' => _x( 'Media', 'post type general name' ),
  71. 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
  72. 'add_new' => _x( 'Add New', 'add new media' ),
  73. 'edit_item' => __( 'Edit Media' ),
  74. 'view_item' => __( 'View Attachment Page' ),
  75. 'attributes' => __( 'Attachment Attributes' ),
  76. ),
  77. 'public' => true,
  78. 'show_ui' => true,
  79. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  80. '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
  81. 'capability_type' => 'post',
  82. 'capabilities' => array(
  83. 'create_posts' => 'upload_files',
  84. ),
  85. 'map_meta_cap' => true,
  86. 'menu_icon' => 'dashicons-admin-media',
  87. 'hierarchical' => false,
  88. 'rewrite' => false,
  89. 'query_var' => false,
  90. 'show_in_nav_menus' => false,
  91. 'delete_with_user' => true,
  92. 'supports' => array( 'title', 'author', 'comments' ),
  93. 'show_in_rest' => true,
  94. 'rest_base' => 'media',
  95. 'rest_controller_class' => 'WP_REST_Attachments_Controller',
  96. )
  97. );
  98. add_post_type_support( 'attachment:audio', 'thumbnail' );
  99. add_post_type_support( 'attachment:video', 'thumbnail' );
  100. register_post_type(
  101. 'revision',
  102. array(
  103. 'labels' => array(
  104. 'name' => __( 'Revisions' ),
  105. 'singular_name' => __( 'Revision' ),
  106. ),
  107. 'public' => false,
  108. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  109. '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
  110. 'capability_type' => 'post',
  111. 'map_meta_cap' => true,
  112. 'hierarchical' => false,
  113. 'rewrite' => false,
  114. 'query_var' => false,
  115. 'can_export' => false,
  116. 'delete_with_user' => true,
  117. 'supports' => array( 'author' ),
  118. )
  119. );
  120. register_post_type(
  121. 'nav_menu_item',
  122. array(
  123. 'labels' => array(
  124. 'name' => __( 'Navigation Menu Items' ),
  125. 'singular_name' => __( 'Navigation Menu Item' ),
  126. ),
  127. 'public' => false,
  128. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  129. 'hierarchical' => false,
  130. 'rewrite' => false,
  131. 'delete_with_user' => false,
  132. 'query_var' => false,
  133. )
  134. );
  135. register_post_type(
  136. 'custom_css',
  137. array(
  138. 'labels' => array(
  139. 'name' => __( 'Custom CSS' ),
  140. 'singular_name' => __( 'Custom CSS' ),
  141. ),
  142. 'public' => false,
  143. 'hierarchical' => false,
  144. 'rewrite' => false,
  145. 'query_var' => false,
  146. 'delete_with_user' => false,
  147. 'can_export' => true,
  148. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  149. 'supports' => array( 'title', 'revisions' ),
  150. 'capabilities' => array(
  151. 'delete_posts' => 'edit_theme_options',
  152. 'delete_post' => 'edit_theme_options',
  153. 'delete_published_posts' => 'edit_theme_options',
  154. 'delete_private_posts' => 'edit_theme_options',
  155. 'delete_others_posts' => 'edit_theme_options',
  156. 'edit_post' => 'edit_css',
  157. 'edit_posts' => 'edit_css',
  158. 'edit_others_posts' => 'edit_css',
  159. 'edit_published_posts' => 'edit_css',
  160. 'read_post' => 'read',
  161. 'read_private_posts' => 'read',
  162. 'publish_posts' => 'edit_theme_options',
  163. ),
  164. )
  165. );
  166. register_post_type(
  167. 'customize_changeset',
  168. array(
  169. 'labels' => array(
  170. 'name' => _x( 'Changesets', 'post type general name' ),
  171. 'singular_name' => _x( 'Changeset', 'post type singular name' ),
  172. 'add_new' => _x( 'Add New', 'Customize Changeset' ),
  173. 'add_new_item' => __( 'Add New Changeset' ),
  174. 'new_item' => __( 'New Changeset' ),
  175. 'edit_item' => __( 'Edit Changeset' ),
  176. 'view_item' => __( 'View Changeset' ),
  177. 'all_items' => __( 'All Changesets' ),
  178. 'search_items' => __( 'Search Changesets' ),
  179. 'not_found' => __( 'No changesets found.' ),
  180. 'not_found_in_trash' => __( 'No changesets found in Trash.' ),
  181. ),
  182. 'public' => false,
  183. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  184. 'map_meta_cap' => true,
  185. 'hierarchical' => false,
  186. 'rewrite' => false,
  187. 'query_var' => false,
  188. 'can_export' => false,
  189. 'delete_with_user' => false,
  190. 'supports' => array( 'title', 'author' ),
  191. 'capability_type' => 'customize_changeset',
  192. 'capabilities' => array(
  193. 'create_posts' => 'customize',
  194. 'delete_others_posts' => 'customize',
  195. 'delete_post' => 'customize',
  196. 'delete_posts' => 'customize',
  197. 'delete_private_posts' => 'customize',
  198. 'delete_published_posts' => 'customize',
  199. 'edit_others_posts' => 'customize',
  200. 'edit_post' => 'customize',
  201. 'edit_posts' => 'customize',
  202. 'edit_private_posts' => 'customize',
  203. 'edit_published_posts' => 'do_not_allow',
  204. 'publish_posts' => 'customize',
  205. 'read' => 'read',
  206. 'read_post' => 'customize',
  207. 'read_private_posts' => 'customize',
  208. ),
  209. )
  210. );
  211. register_post_type(
  212. 'oembed_cache',
  213. array(
  214. 'labels' => array(
  215. 'name' => __( 'oEmbed Responses' ),
  216. 'singular_name' => __( 'oEmbed Response' ),
  217. ),
  218. 'public' => false,
  219. 'hierarchical' => false,
  220. 'rewrite' => false,
  221. 'query_var' => false,
  222. 'delete_with_user' => false,
  223. 'can_export' => false,
  224. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  225. 'supports' => array(),
  226. )
  227. );
  228. register_post_type(
  229. 'user_request',
  230. array(
  231. 'labels' => array(
  232. 'name' => __( 'User Requests' ),
  233. 'singular_name' => __( 'User Request' ),
  234. ),
  235. 'public' => false,
  236. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  237. 'hierarchical' => false,
  238. 'rewrite' => false,
  239. 'query_var' => false,
  240. 'can_export' => false,
  241. 'delete_with_user' => false,
  242. 'supports' => array(),
  243. )
  244. );
  245. register_post_type(
  246. 'wp_block',
  247. array(
  248. 'labels' => array(
  249. 'name' => _x( 'Reusable blocks', 'post type general name' ),
  250. 'singular_name' => _x( 'Reusable block', 'post type singular name' ),
  251. 'add_new' => _x( 'Add New', 'Reusable block' ),
  252. 'add_new_item' => __( 'Add new Reusable block' ),
  253. 'new_item' => __( 'New Reusable block' ),
  254. 'edit_item' => __( 'Edit Reusable block' ),
  255. 'view_item' => __( 'View Reusable block' ),
  256. 'all_items' => __( 'All Reusable blocks' ),
  257. 'search_items' => __( 'Search Reusable blocks' ),
  258. 'not_found' => __( 'No reusable blocks found.' ),
  259. 'not_found_in_trash' => __( 'No reusable blocks found in Trash.' ),
  260. 'filter_items_list' => __( 'Filter reusable blocks list' ),
  261. 'items_list_navigation' => __( 'Reusable blocks list navigation' ),
  262. 'items_list' => __( 'Reusable blocks list' ),
  263. 'item_published' => __( 'Reusable block published.' ),
  264. 'item_published_privately' => __( 'Reusable block published privately.' ),
  265. 'item_reverted_to_draft' => __( 'Reusable block reverted to draft.' ),
  266. 'item_scheduled' => __( 'Reusable block scheduled.' ),
  267. 'item_updated' => __( 'Reusable block updated.' ),
  268. ),
  269. 'public' => false,
  270. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  271. 'show_ui' => true,
  272. 'show_in_menu' => false,
  273. 'rewrite' => false,
  274. 'show_in_rest' => true,
  275. 'rest_base' => 'blocks',
  276. 'rest_controller_class' => 'WP_REST_Blocks_Controller',
  277. 'capability_type' => 'block',
  278. 'capabilities' => array(
  279. // You need to be able to edit posts, in order to read blocks in their raw form.
  280. 'read' => 'edit_posts',
  281. // You need to be able to publish posts, in order to create blocks.
  282. 'create_posts' => 'publish_posts',
  283. 'edit_posts' => 'edit_posts',
  284. 'edit_published_posts' => 'edit_published_posts',
  285. 'delete_published_posts' => 'delete_published_posts',
  286. 'edit_others_posts' => 'edit_others_posts',
  287. 'delete_others_posts' => 'delete_others_posts',
  288. ),
  289. 'map_meta_cap' => true,
  290. 'supports' => array(
  291. 'title',
  292. 'editor',
  293. 'revisions',
  294. ),
  295. )
  296. );
  297. register_post_type(
  298. 'wp_template',
  299. array(
  300. 'labels' => array(
  301. 'name' => __( 'Templates' ),
  302. 'singular_name' => __( 'Template' ),
  303. 'add_new' => _x( 'Add New', 'Template' ),
  304. 'add_new_item' => __( 'Add New Template' ),
  305. 'new_item' => __( 'New Template' ),
  306. 'edit_item' => __( 'Edit Template' ),
  307. 'view_item' => __( 'View Template' ),
  308. 'all_items' => __( 'All Templates' ),
  309. 'search_items' => __( 'Search Templates' ),
  310. 'parent_item_colon' => __( 'Parent Template:' ),
  311. 'not_found' => __( 'No templates found.' ),
  312. 'not_found_in_trash' => __( 'No templates found in Trash.' ),
  313. 'archives' => __( 'Template archives' ),
  314. 'insert_into_item' => __( 'Insert into template' ),
  315. 'uploaded_to_this_item' => __( 'Uploaded to this template' ),
  316. 'filter_items_list' => __( 'Filter templates list' ),
  317. 'items_list_navigation' => __( 'Templates list navigation' ),
  318. 'items_list' => __( 'Templates list' ),
  319. ),
  320. 'description' => __( 'Templates to include in your theme.' ),
  321. 'public' => false,
  322. '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
  323. 'has_archive' => false,
  324. 'show_ui' => false,
  325. 'show_in_menu' => false,
  326. 'show_in_rest' => true,
  327. 'rewrite' => false,
  328. 'rest_base' => 'templates',
  329. 'rest_controller_class' => 'WP_REST_Templates_Controller',
  330. 'capability_type' => array( 'template', 'templates' ),
  331. 'capabilities' => array(
  332. 'create_posts' => 'edit_theme_options',
  333. 'delete_posts' => 'edit_theme_options',
  334. 'delete_others_posts' => 'edit_theme_options',
  335. 'delete_private_posts' => 'edit_theme_options',
  336. 'delete_published_posts' => 'edit_theme_options',
  337. 'edit_posts' => 'edit_theme_options',
  338. 'edit_others_posts' => 'edit_theme_options',
  339. 'edit_private_posts' => 'edit_theme_options',
  340. 'edit_published_posts' => 'edit_theme_options',
  341. 'publish_posts' => 'edit_theme_options',
  342. 'read' => 'edit_theme_options',
  343. 'read_private_posts' => 'edit_theme_options',
  344. ),
  345. 'map_meta_cap' => true,
  346. 'supports' => array(
  347. 'title',
  348. 'slug',
  349. 'excerpt',
  350. 'editor',
  351. 'revisions',
  352. ),
  353. )
  354. );
  355. register_post_status(
  356. 'publish',
  357. array(
  358. 'label' => _x( 'Published', 'post status' ),
  359. 'public' => true,
  360. '_builtin' => true, /* internal use only. */
  361. /* translators: %s: Number of published posts. */
  362. 'label_count' => _n_noop(
  363. 'Published <span class="count">(%s)</span>',
  364. 'Published <span class="count">(%s)</span>'
  365. ),
  366. )
  367. );
  368. register_post_status(
  369. 'future',
  370. array(
  371. 'label' => _x( 'Scheduled', 'post status' ),
  372. 'protected' => true,
  373. '_builtin' => true, /* internal use only. */
  374. /* translators: %s: Number of scheduled posts. */
  375. 'label_count' => _n_noop(
  376. 'Scheduled <span class="count">(%s)</span>',
  377. 'Scheduled <span class="count">(%s)</span>'
  378. ),
  379. )
  380. );
  381. register_post_status(
  382. 'draft',
  383. array(
  384. 'label' => _x( 'Draft', 'post status' ),
  385. 'protected' => true,
  386. '_builtin' => true, /* internal use only. */
  387. /* translators: %s: Number of draft posts. */
  388. 'label_count' => _n_noop(
  389. 'Draft <span class="count">(%s)</span>',
  390. 'Drafts <span class="count">(%s)</span>'
  391. ),
  392. 'date_floating' => true,
  393. )
  394. );
  395. register_post_status(
  396. 'pending',
  397. array(
  398. 'label' => _x( 'Pending', 'post status' ),
  399. 'protected' => true,
  400. '_builtin' => true, /* internal use only. */
  401. /* translators: %s: Number of pending posts. */
  402. 'label_count' => _n_noop(
  403. 'Pending <span class="count">(%s)</span>',
  404. 'Pending <span class="count">(%s)</span>'
  405. ),
  406. 'date_floating' => true,
  407. )
  408. );
  409. register_post_status(
  410. 'private',
  411. array(
  412. 'label' => _x( 'Private', 'post status' ),
  413. 'private' => true,
  414. '_builtin' => true, /* internal use only. */
  415. /* translators: %s: Number of private posts. */
  416. 'label_count' => _n_noop(
  417. 'Private <span class="count">(%s)</span>',
  418. 'Private <span class="count">(%s)</span>'
  419. ),
  420. )
  421. );
  422. register_post_status(
  423. 'trash',
  424. array(
  425. 'label' => _x( 'Trash', 'post status' ),
  426. 'internal' => true,
  427. '_builtin' => true, /* internal use only. */
  428. /* translators: %s: Number of trashed posts. */
  429. 'label_count' => _n_noop(
  430. 'Trash <span class="count">(%s)</span>',
  431. 'Trash <span class="count">(%s)</span>'
  432. ),
  433. 'show_in_admin_status_list' => true,
  434. )
  435. );
  436. register_post_status(
  437. 'auto-draft',
  438. array(
  439. 'label' => 'auto-draft',
  440. 'internal' => true,
  441. '_builtin' => true, /* internal use only. */
  442. 'date_floating' => true,
  443. )
  444. );
  445. register_post_status(
  446. 'inherit',
  447. array(
  448. 'label' => 'inherit',
  449. 'internal' => true,
  450. '_builtin' => true, /* internal use only. */
  451. 'exclude_from_search' => false,
  452. )
  453. );
  454. register_post_status(
  455. 'request-pending',
  456. array(
  457. 'label' => _x( 'Pending', 'request status' ),
  458. 'internal' => true,
  459. '_builtin' => true, /* internal use only. */
  460. /* translators: %s: Number of pending requests. */
  461. 'label_count' => _n_noop(
  462. 'Pending <span class="count">(%s)</span>',
  463. 'Pending <span class="count">(%s)</span>'
  464. ),
  465. 'exclude_from_search' => false,
  466. )
  467. );
  468. register_post_status(
  469. 'request-confirmed',
  470. array(
  471. 'label' => _x( 'Confirmed', 'request status' ),
  472. 'internal' => true,
  473. '_builtin' => true, /* internal use only. */
  474. /* translators: %s: Number of confirmed requests. */
  475. 'label_count' => _n_noop(
  476. 'Confirmed <span class="count">(%s)</span>',
  477. 'Confirmed <span class="count">(%s)</span>'
  478. ),
  479. 'exclude_from_search' => false,
  480. )
  481. );
  482. register_post_status(
  483. 'request-failed',
  484. array(
  485. 'label' => _x( 'Failed', 'request status' ),
  486. 'internal' => true,
  487. '_builtin' => true, /* internal use only. */
  488. /* translators: %s: Number of failed requests. */
  489. 'label_count' => _n_noop(
  490. 'Failed <span class="count">(%s)</span>',
  491. 'Failed <span class="count">(%s)</span>'
  492. ),
  493. 'exclude_from_search' => false,
  494. )
  495. );
  496. register_post_status(
  497. 'request-completed',
  498. array(
  499. 'label' => _x( 'Completed', 'request status' ),
  500. 'internal' => true,
  501. '_builtin' => true, /* internal use only. */
  502. /* translators: %s: Number of completed requests. */
  503. 'label_count' => _n_noop(
  504. 'Completed <span class="count">(%s)</span>',
  505. 'Completed <span class="count">(%s)</span>'
  506. ),
  507. 'exclude_from_search' => false,
  508. )
  509. );
  510. }
  511. /**
  512. * Retrieve attached file path based on attachment ID.
  513. *
  514. * By default the path will go through the 'get_attached_file' filter, but
  515. * passing a true to the $unfiltered argument of get_attached_file() will
  516. * return the file path unfiltered.
  517. *
  518. * The function works by getting the single post meta name, named
  519. * '_wp_attached_file' and returning it. This is a convenience function to
  520. * prevent looking up the meta name and provide a mechanism for sending the
  521. * attached filename through a filter.
  522. *
  523. * @since 2.0.0
  524. *
  525. * @param int $attachment_id Attachment ID.
  526. * @param bool $unfiltered Optional. Whether to apply filters. Default false.
  527. * @return string|false The file path to where the attached file should be, false otherwise.
  528. */
  529. function get_attached_file( $attachment_id, $unfiltered = false ) {
  530. $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
  531. // If the file is relative, prepend upload dir.
  532. if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
  533. $uploads = wp_get_upload_dir();
  534. if ( false === $uploads['error'] ) {
  535. $file = $uploads['basedir'] . "/$file";
  536. }
  537. }
  538. if ( $unfiltered ) {
  539. return $file;
  540. }
  541. /**
  542. * Filters the attached file based on the given ID.
  543. *
  544. * @since 2.1.0
  545. *
  546. * @param string|false $file The file path to where the attached file should be, false otherwise.
  547. * @param int $attachment_id Attachment ID.
  548. */
  549. return apply_filters( 'get_attached_file', $file, $attachment_id );
  550. }
  551. /**
  552. * Update attachment file path based on attachment ID.
  553. *
  554. * Used to update the file path of the attachment, which uses post meta name
  555. * '_wp_attached_file' to store the path of the attachment.
  556. *
  557. * @since 2.1.0
  558. *
  559. * @param int $attachment_id Attachment ID.
  560. * @param string $file File path for the attachment.
  561. * @return bool True on success, false on failure.
  562. */
  563. function update_attached_file( $attachment_id, $file ) {
  564. if ( ! get_post( $attachment_id ) ) {
  565. return false;
  566. }
  567. /**
  568. * Filters the path to the attached file to update.
  569. *
  570. * @since 2.1.0
  571. *
  572. * @param string $file Path to the attached file to update.
  573. * @param int $attachment_id Attachment ID.
  574. */
  575. $file = apply_filters( 'update_attached_file', $file, $attachment_id );
  576. $file = _wp_relative_upload_path( $file );
  577. if ( $file ) {
  578. return update_post_meta( $attachment_id, '_wp_attached_file', $file );
  579. } else {
  580. return delete_post_meta( $attachment_id, '_wp_attached_file' );
  581. }
  582. }
  583. /**
  584. * Return relative path to an uploaded file.
  585. *
  586. * The path is relative to the current upload dir.
  587. *
  588. * @since 2.9.0
  589. * @access private
  590. *
  591. * @param string $path Full path to the file.
  592. * @return string Relative path on success, unchanged path on failure.
  593. */
  594. function _wp_relative_upload_path( $path ) {
  595. $new_path = $path;
  596. $uploads = wp_get_upload_dir();
  597. if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
  598. $new_path = str_replace( $uploads['basedir'], '', $new_path );
  599. $new_path = ltrim( $new_path, '/' );
  600. }
  601. /**
  602. * Filters the relative path to an uploaded file.
  603. *
  604. * @since 2.9.0
  605. *
  606. * @param string $new_path Relative path to the file.
  607. * @param string $path Full path to the file.
  608. */
  609. return apply_filters( '_wp_relative_upload_path', $new_path, $path );
  610. }
  611. /**
  612. * Retrieve all children of the post parent ID.
  613. *
  614. * Normally, without any enhancements, the children would apply to pages. In the
  615. * context of the inner workings of WordPress, pages, posts, and attachments
  616. * share the same table, so therefore the functionality could apply to any one
  617. * of them. It is then noted that while this function does not work on posts, it
  618. * does not mean that it won't work on posts. It is recommended that you know
  619. * what context you wish to retrieve the children of.
  620. *
  621. * Attachments may also be made the child of a post, so if that is an accurate
  622. * statement (which needs to be verified), it would then be possible to get
  623. * all of the attachments for a post. Attachments have since changed since
  624. * version 2.5, so this is most likely inaccurate, but serves generally as an
  625. * example of what is possible.
  626. *
  627. * The arguments listed as defaults are for this function and also of the
  628. * get_posts() function. The arguments are combined with the get_children defaults
  629. * and are then passed to the get_posts() function, which accepts additional arguments.
  630. * You can replace the defaults in this function, listed below and the additional
  631. * arguments listed in the get_posts() function.
  632. *
  633. * The 'post_parent' is the most important argument and important attention
  634. * needs to be paid to the $args parameter. If you pass either an object or an
  635. * integer (number), then just the 'post_parent' is grabbed and everything else
  636. * is lost. If you don't specify any arguments, then it is assumed that you are
  637. * in The Loop and the post parent will be grabbed for from the current post.
  638. *
  639. * The 'post_parent' argument is the ID to get the children. The 'numberposts'
  640. * is the amount of posts to retrieve that has a default of '-1', which is
  641. * used to get all of the posts. Giving a number higher than 0 will only
  642. * retrieve that amount of posts.
  643. *
  644. * The 'post_type' and 'post_status' arguments can be used to choose what
  645. * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
  646. * post types are 'post', 'pages', and 'attachments'. The 'post_status'
  647. * argument will accept any post status within the write administration panels.
  648. *
  649. * @since 2.0.0
  650. *
  651. * @see get_posts()
  652. * @todo Check validity of description.
  653. *
  654. * @global WP_Post $post Global post object.
  655. *
  656. * @param mixed $args Optional. User defined arguments for replacing the defaults. Default empty.
  657. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  658. * correspond to a WP_Post object, an associative array, or a numeric array,
  659. * respectively. Default OBJECT.
  660. * @return WP_Post[]|int[] Array of post objects or post IDs.
  661. */
  662. function get_children( $args = '', $output = OBJECT ) {
  663. $kids = array();
  664. if ( empty( $args ) ) {
  665. if ( isset( $GLOBALS['post'] ) ) {
  666. $args = array( 'post_parent' => (int) $GLOBALS['post']->post_parent );
  667. } else {
  668. return $kids;
  669. }
  670. } elseif ( is_object( $args ) ) {
  671. $args = array( 'post_parent' => (int) $args->post_parent );
  672. } elseif ( is_numeric( $args ) ) {
  673. $args = array( 'post_parent' => (int) $args );
  674. }
  675. $defaults = array(
  676. 'numberposts' => -1,
  677. 'post_type' => 'any',
  678. 'post_status' => 'any',
  679. 'post_parent' => 0,
  680. );
  681. $parsed_args = wp_parse_args( $args, $defaults );
  682. $children = get_posts( $parsed_args );
  683. if ( ! $children ) {
  684. return $kids;
  685. }
  686. if ( ! empty( $parsed_args['fields'] ) ) {
  687. return $children;
  688. }
  689. update_post_cache( $children );
  690. foreach ( $children as $key => $child ) {
  691. $kids[ $child->ID ] = $children[ $key ];
  692. }
  693. if ( OBJECT === $output ) {
  694. return $kids;
  695. } elseif ( ARRAY_A === $output ) {
  696. $weeuns = array();
  697. foreach ( (array) $kids as $kid ) {
  698. $weeuns[ $kid->ID ] = get_object_vars( $kids[ $kid->ID ] );
  699. }
  700. return $weeuns;
  701. } elseif ( ARRAY_N === $output ) {
  702. $babes = array();
  703. foreach ( (array) $kids as $kid ) {
  704. $babes[ $kid->ID ] = array_values( get_object_vars( $kids[ $kid->ID ] ) );
  705. }
  706. return $babes;
  707. } else {
  708. return $kids;
  709. }
  710. }
  711. /**
  712. * Get extended entry info (<!--more-->).
  713. *
  714. * There should not be any space after the second dash and before the word
  715. * 'more'. There can be text or space(s) after the word 'more', but won't be
  716. * referenced.
  717. *
  718. * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
  719. * the `<!--more-->`. The 'extended' key has the content after the
  720. * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
  721. *
  722. * @since 1.0.0
  723. *
  724. * @param string $post Post content.
  725. * @return string[] {
  726. * Extended entry info.
  727. *
  728. * @type string $main Content before the more tag.
  729. * @type string $extended Content after the more tag.
  730. * @type string $more_text Custom read more text, or empty string.
  731. * }
  732. */
  733. function get_extended( $post ) {
  734. // Match the new style more links.
  735. if ( preg_match( '/<!--more(.*?)?-->/', $post, $matches ) ) {
  736. list($main, $extended) = explode( $matches[0], $post, 2 );
  737. $more_text = $matches[1];
  738. } else {
  739. $main = $post;
  740. $extended = '';
  741. $more_text = '';
  742. }
  743. // Leading and trailing whitespace.
  744. $main = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $main );
  745. $extended = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $extended );
  746. $more_text = preg_replace( '/^[\s]*(.*)[\s]*$/', '\\1', $more_text );
  747. return array(
  748. 'main' => $main,
  749. 'extended' => $extended,
  750. 'more_text' => $more_text,
  751. );
  752. }
  753. /**
  754. * Retrieves post data given a post ID or post object.
  755. *
  756. * See sanitize_post() for optional $filter values. Also, the parameter
  757. * `$post`, must be given as a variable, since it is passed by reference.
  758. *
  759. * @since 1.5.1
  760. *
  761. * @global WP_Post $post Global post object.
  762. *
  763. * @param int|WP_Post|null $post Optional. Post ID or post object. `null`, `false`, `0` and other PHP falsey
  764. * values return the current global post inside the loop. A numerically valid post
  765. * ID that points to a non-existent post returns `null`. Defaults to global $post.
  766. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  767. * correspond to a WP_Post object, an associative array, or a numeric array,
  768. * respectively. Default OBJECT.
  769. * @param string $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
  770. * or 'display'. Default 'raw'.
  771. * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
  772. * When $output is OBJECT, a `WP_Post` instance is returned.
  773. */
  774. function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
  775. if ( empty( $post ) && isset( $GLOBALS['post'] ) ) {
  776. $post = $GLOBALS['post'];
  777. }
  778. if ( $post instanceof WP_Post ) {
  779. $_post = $post;
  780. } elseif ( is_object( $post ) ) {
  781. if ( empty( $post->filter ) ) {
  782. $_post = sanitize_post( $post, 'raw' );
  783. $_post = new WP_Post( $_post );
  784. } elseif ( 'raw' === $post->filter ) {
  785. $_post = new WP_Post( $post );
  786. } else {
  787. $_post = WP_Post::get_instance( $post->ID );
  788. }
  789. } else {
  790. $_post = WP_Post::get_instance( $post );
  791. }
  792. if ( ! $_post ) {
  793. return null;
  794. }
  795. $_post = $_post->filter( $filter );
  796. if ( ARRAY_A === $output ) {
  797. return $_post->to_array();
  798. } elseif ( ARRAY_N === $output ) {
  799. return array_values( $_post->to_array() );
  800. }
  801. return $_post;
  802. }
  803. /**
  804. * Retrieves the IDs of the ancestors of a post.
  805. *
  806. * @since 2.5.0
  807. *
  808. * @param int|WP_Post $post Post ID or post object.
  809. * @return int[] Array of ancestor IDs or empty array if there are none.
  810. */
  811. function get_post_ancestors( $post ) {
  812. $post = get_post( $post );
  813. if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID ) {
  814. return array();
  815. }
  816. $ancestors = array();
  817. $id = $post->post_parent;
  818. $ancestors[] = $id;
  819. while ( $ancestor = get_post( $id ) ) {
  820. // Loop detection: If the ancestor has been seen before, break.
  821. if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors, true ) ) {
  822. break;
  823. }
  824. $id = $ancestor->post_parent;
  825. $ancestors[] = $id;
  826. }
  827. return $ancestors;
  828. }
  829. /**
  830. * Retrieve data from a post field based on Post ID.
  831. *
  832. * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
  833. * etc and based off of the post object property or key names.
  834. *
  835. * The context values are based off of the taxonomy filter functions and
  836. * supported values are found within those functions.
  837. *
  838. * @since 2.3.0
  839. * @since 4.5.0 The `$post` parameter was made optional.
  840. *
  841. * @see sanitize_post_field()
  842. *
  843. * @param string $field Post field name.
  844. * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
  845. * @param string $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
  846. * or 'display'. Default 'display'.
  847. * @return string The value of the post field on success, empty string on failure.
  848. */
  849. function get_post_field( $field, $post = null, $context = 'display' ) {
  850. $post = get_post( $post );
  851. if ( ! $post ) {
  852. return '';
  853. }
  854. if ( ! isset( $post->$field ) ) {
  855. return '';
  856. }
  857. return sanitize_post_field( $field, $post->$field, $post->ID, $context );
  858. }
  859. /**
  860. * Retrieve the mime type of an attachment based on the ID.
  861. *
  862. * This function can be used with any post type, but it makes more sense with
  863. * attachments.
  864. *
  865. * @since 2.0.0
  866. *
  867. * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post.
  868. * @return string|false The mime type on success, false on failure.
  869. */
  870. function get_post_mime_type( $post = null ) {
  871. $post = get_post( $post );
  872. if ( is_object( $post ) ) {
  873. return $post->post_mime_type;
  874. }
  875. return false;
  876. }
  877. /**
  878. * Retrieve the post status based on the post ID.
  879. *
  880. * If the post ID is of an attachment, then the parent post status will be given
  881. * instead.
  882. *
  883. * @since 2.0.0
  884. *
  885. * @param int|WP_Post $post Optional. Post ID or post object. Defaults to global $post..
  886. * @return string|false Post status on success, false on failure.
  887. */
  888. function get_post_status( $post = null ) {
  889. $post = get_post( $post );
  890. if ( ! is_object( $post ) ) {
  891. return false;
  892. }
  893. $post_status = $post->post_status;
  894. if (
  895. 'attachment' === $post->post_type &&
  896. 'inherit' === $post_status
  897. ) {
  898. if (
  899. 0 === $post->post_parent ||
  900. ! get_post( $post->post_parent ) ||
  901. $post->ID === $post->post_parent
  902. ) {
  903. // Unattached attachments with inherit status are assumed to be published.
  904. $post_status = 'publish';
  905. } elseif ( 'trash' === get_post_status( $post->post_parent ) ) {
  906. // Get parent status prior to trashing.
  907. $post_status = get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
  908. if ( ! $post_status ) {
  909. // Assume publish as above.
  910. $post_status = 'publish';
  911. }
  912. } else {
  913. $post_status = get_post_status( $post->post_parent );
  914. }
  915. } elseif (
  916. 'attachment' === $post->post_type &&
  917. ! in_array( $post_status, array( 'private', 'trash', 'auto-draft' ), true )
  918. ) {
  919. /*
  920. * Ensure uninherited attachments have a permitted status either 'private', 'trash', 'auto-draft'.
  921. * This is to match the logic in wp_insert_post().
  922. *
  923. * Note: 'inherit' is excluded from this check as it is resolved to the parent post's
  924. * status in the logic block above.
  925. */
  926. $post_status = 'publish';
  927. }
  928. /**
  929. * Filters the post status.
  930. *
  931. * @since 4.4.0
  932. * @since 5.7.0 The attachment post type is now passed through this filter.
  933. *
  934. * @param string $post_status The post status.
  935. * @param WP_Post $post The post object.
  936. */
  937. return apply_filters( 'get_post_status', $post_status, $post );
  938. }
  939. /**
  940. * Retrieve all of the WordPress supported post statuses.
  941. *
  942. * Posts have a limited set of valid status values, this provides the
  943. * post_status values and descriptions.
  944. *
  945. * @since 2.5.0
  946. *
  947. * @return string[] Array of post status labels keyed by their status.
  948. */
  949. function get_post_statuses() {
  950. $status = array(
  951. 'draft' => __( 'Draft' ),
  952. 'pending' => __( 'Pending Review' ),
  953. 'private' => __( 'Private' ),
  954. 'publish' => __( 'Published' ),
  955. );
  956. return $status;
  957. }
  958. /**
  959. * Retrieve all of the WordPress support page statuses.
  960. *
  961. * Pages have a limited set of valid status values, this provides the
  962. * post_status values and descriptions.
  963. *
  964. * @since 2.5.0
  965. *
  966. * @return string[] Array of page status labels keyed by their status.
  967. */
  968. function get_page_statuses() {
  969. $status = array(
  970. 'draft' => __( 'Draft' ),
  971. 'private' => __( 'Private' ),
  972. 'publish' => __( 'Published' ),
  973. );
  974. return $status;
  975. }
  976. /**
  977. * Return statuses for privacy requests.
  978. *
  979. * @since 4.9.6
  980. * @access private
  981. *
  982. * @return array
  983. */
  984. function _wp_privacy_statuses() {
  985. return array(
  986. 'request-pending' => _x( 'Pending', 'request status' ), // Pending confirmation from user.
  987. 'request-confirmed' => _x( 'Confirmed', 'request status' ), // User has confirmed the action.
  988. 'request-failed' => _x( 'Failed', 'request status' ), // User failed to confirm the action.
  989. 'request-completed' => _x( 'Completed', 'request status' ), // Admin has handled the request.
  990. );
  991. }
  992. /**
  993. * Register a post status. Do not use before init.
  994. *
  995. * A simple function for creating or modifying a post status based on the
  996. * parameters given. The function will accept an array (second optional
  997. * parameter), along with a string for the post status name.
  998. *
  999. * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
  1000. *
  1001. * @since 3.0.0
  1002. *
  1003. * @global array $wp_post_statuses Inserts new post status object into the list
  1004. *
  1005. * @param string $post_status Name of the post status.
  1006. * @param array|string $args {
  1007. * Optional. Array or string of post status arguments.
  1008. *
  1009. * @type bool|string $label A descriptive name for the post status marked
  1010. * for translation. Defaults to value of $post_status.
  1011. * @type bool|array $label_count Descriptive text to use for nooped plurals.
  1012. * Default array of $label, twice.
  1013. * @type bool $exclude_from_search Whether to exclude posts with this post status
  1014. * from search results. Default is value of $internal.
  1015. * @type bool $_builtin Whether the status is built-in. Core-use only.
  1016. * Default false.
  1017. * @type bool $public Whether posts of this status should be shown
  1018. * in the front end of the site. Default false.
  1019. * @type bool $internal Whether the status is for internal use only.
  1020. * Default false.
  1021. * @type bool $protected Whether posts with this status should be protected.
  1022. * Default false.
  1023. * @type bool $private Whether posts with this status should be private.
  1024. * Default false.
  1025. * @type bool $publicly_queryable Whether posts with this status should be publicly-
  1026. * queryable. Default is value of $public.
  1027. * @type bool $show_in_admin_all_list Whether to include posts in the edit listing for
  1028. * their post type. Default is the opposite value
  1029. * of $internal.
  1030. * @type bool $show_in_admin_status_list Show in the list of statuses with post counts at
  1031. * the top of the edit listings,
  1032. * e.g. All (12) | Published (9) | My Custom Status (2)
  1033. * Default is the opposite value of $internal.
  1034. * @type bool $date_floating Whether the post has a floating creation date.
  1035. * Default to false.
  1036. * }
  1037. * @return object
  1038. */
  1039. function register_post_status( $post_status, $args = array() ) {
  1040. global $wp_post_statuses;
  1041. if ( ! is_array( $wp_post_statuses ) ) {
  1042. $wp_post_statuses = array();
  1043. }
  1044. // Args prefixed with an underscore are reserved for internal use.
  1045. $defaults = array(
  1046. 'label' => false,
  1047. 'label_count' => false,
  1048. 'exclude_from_search' => null,
  1049. '_builtin' => false,
  1050. 'public' => null,
  1051. 'internal' => null,
  1052. 'protected' => null,
  1053. 'private' => null,
  1054. 'publicly_queryable' => null,
  1055. 'show_in_admin_status_list' => null,
  1056. 'show_in_admin_all_list' => null,
  1057. 'date_floating' => null,
  1058. );
  1059. $args = wp_parse_args( $args, $defaults );
  1060. $args = (object) $args;
  1061. $post_status = sanitize_key( $post_status );
  1062. $args->name = $post_status;
  1063. // Set various defaults.
  1064. if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private ) {
  1065. $args->internal = true;
  1066. }
  1067. if ( null === $args->public ) {
  1068. $args->public = false;
  1069. }
  1070. if ( null === $args->private ) {
  1071. $args->private = false;
  1072. }
  1073. if ( null === $args->protected ) {
  1074. $args->protected = false;
  1075. }
  1076. if ( null === $args->internal ) {
  1077. $args->internal = false;
  1078. }
  1079. if ( null === $args->publicly_queryable ) {
  1080. $args->publicly_queryable = $args->public;
  1081. }
  1082. if ( null === $args->exclude_from_search ) {
  1083. $args->exclude_from_search = $args->internal;
  1084. }
  1085. if ( null === $args->show_in_admin_all_list ) {
  1086. $args->show_in_admin_all_list = ! $args->internal;
  1087. }
  1088. if ( null === $args->show_in_admin_status_list ) {
  1089. $args->show_in_admin_status_list = ! $args->internal;
  1090. }
  1091. if ( null === $args->date_floating ) {
  1092. $args->date_floating = false;
  1093. }
  1094. if ( false === $args->label ) {
  1095. $args->label = $post_status;
  1096. }
  1097. if ( false === $args->label_count ) {
  1098. // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralSingle,WordPress.WP.I18n.NonSingularStringLiteralPlural
  1099. $args->label_count = _n_noop( $args->label, $args->label );
  1100. }
  1101. $wp_post_statuses[ $post_status ] = $args;
  1102. return $args;
  1103. }
  1104. /**
  1105. * Retrieve a post status object by name.
  1106. *
  1107. * @since 3.0.0
  1108. *
  1109. * @global array $wp_post_statuses List of post statuses.
  1110. *
  1111. * @see register_post_status()
  1112. *
  1113. * @param string $post_status The name of a registered post status.
  1114. * @return object|null A post status object.
  1115. */
  1116. function get_post_status_object( $post_status ) {
  1117. global $wp_post_statuses;
  1118. if ( empty( $wp_post_statuses[ $post_status ] ) ) {
  1119. return null;
  1120. }
  1121. return $wp_post_statuses[ $post_status ];
  1122. }
  1123. /**
  1124. * Get a list of post statuses.
  1125. *
  1126. * @since 3.0.0
  1127. *
  1128. * @global array $wp_post_statuses List of post statuses.
  1129. *
  1130. * @see register_post_status()
  1131. *
  1132. * @param array|string $args Optional. Array or string of post status arguments to compare against
  1133. * properties of the global `$wp_post_statuses objects`. Default empty array.
  1134. * @param string $output Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
  1135. * @param string $operator Optional. The logical operation to perform. 'or' means only one element
  1136. * from the array needs to match; 'and' means all elements must match.
  1137. * Default 'and'.
  1138. * @return array A list of post status names or objects.
  1139. */
  1140. function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
  1141. global $wp_post_statuses;
  1142. $field = ( 'names' === $output ) ? 'name' : false;
  1143. return wp_filter_object_list( $wp_post_statuses, $args, $operator, $field );
  1144. }
  1145. /**
  1146. * Whether the post type is hierarchical.
  1147. *
  1148. * A false return value might also mean that the post type does not exist.
  1149. *
  1150. * @since 3.0.0
  1151. *
  1152. * @see get_post_type_object()
  1153. *
  1154. * @param string $post_type Post type name
  1155. * @return bool Whether post type is hierarchical.
  1156. */
  1157. function is_post_type_hierarchical( $post_type ) {
  1158. if ( ! post_type_exists( $post_type ) ) {
  1159. return false;
  1160. }
  1161. $post_type = get_post_type_object( $post_type );
  1162. return $post_type->hierarchical;
  1163. }
  1164. /**
  1165. * Determines whether a post type is registered.
  1166. *
  1167. * For more information on this and similar theme functions, check out
  1168. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1169. * Conditional Tags} article in the Theme Developer Handbook.
  1170. *
  1171. * @since 3.0.0
  1172. *
  1173. * @see get_post_type_object()
  1174. *
  1175. * @param string $post_type Post type name.
  1176. * @return bool Whether post type is registered.
  1177. */
  1178. function post_type_exists( $post_type ) {
  1179. return (bool) get_post_type_object( $post_type );
  1180. }
  1181. /**
  1182. * Retrieves the post type of the current post or of a given post.
  1183. *
  1184. * @since 2.1.0
  1185. *
  1186. * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
  1187. * @return string|false Post type on success, false on failure.
  1188. */
  1189. function get_post_type( $post = null ) {
  1190. $post = get_post( $post );
  1191. if ( $post ) {
  1192. return $post->post_type;
  1193. }
  1194. return false;
  1195. }
  1196. /**
  1197. * Retrieves a post type object by name.
  1198. *
  1199. * @since 3.0.0
  1200. * @since 4.6.0 Object returned is now an instance of `WP_Post_Type`.
  1201. *
  1202. * @global array $wp_post_types List of post types.
  1203. *
  1204. * @see register_post_type()
  1205. *
  1206. * @param string $post_type The name of a registered post type.
  1207. * @return WP_Post_Type|null WP_Post_Type object if it exists, null otherwise.
  1208. */
  1209. function get_post_type_object( $post_type ) {
  1210. global $wp_post_types;
  1211. if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
  1212. return null;
  1213. }
  1214. return $wp_post_types[ $post_type ];
  1215. }
  1216. /**
  1217. * Get a list of all registered post type objects.
  1218. *
  1219. * @since 2.9.0
  1220. *
  1221. * @global array $wp_post_types List of post types.
  1222. *
  1223. * @see register_post_type() for accepted arguments.
  1224. *
  1225. * @param array|string $args Optional. An array of key => value arguments to match against
  1226. * the post type objects. Default empty array.
  1227. * @param string $output Optional. The type of output to return. Accepts post type 'names'
  1228. * or 'objects'. Default 'names'.
  1229. * @param string $operator Optional. The logical operation to perform. 'or' means only one
  1230. * element from the array needs to match; 'and' means all elements
  1231. * must match; 'not' means no elements may match. Default 'and'.
  1232. * @return string[]|WP_Post_Type[] An array of post type names or objects.
  1233. */
  1234. function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
  1235. global $wp_post_types;
  1236. $field = ( 'names' === $output ) ? 'name' : false;
  1237. return wp_filter_object_list( $wp_post_types, $args, $operator, $field );
  1238. }
  1239. /**
  1240. * Registers a post type.
  1241. *
  1242. * Note: Post type registrations should not be hooked before the
  1243. * {@see 'init'} action. Also, any taxonomy connections should be
  1244. * registered via the `$taxonomies` argument to ensure consistency
  1245. * when hooks such as {@see 'parse_query'} or {@see 'pre_get_posts'}
  1246. * are used.
  1247. *
  1248. * Post types can support any number of built-in core features such
  1249. * as meta boxes, custom fields, post thumbnails, post statuses,
  1250. * comments, and more. See the `$supports` argument for a complete
  1251. * list of supported features.
  1252. *
  1253. * @since 2.9.0
  1254. * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
  1255. * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing
  1256. * screen and post editing screen.
  1257. * @since 4.6.0 Post type object returned is now an instance of `WP_Post_Type`.
  1258. * @since 4.7.0 Introduced `show_in_rest`, `rest_base` and `rest_controller_class`
  1259. * arguments to register the post type in REST API.
  1260. * @since 5.0.0 The `template` and `template_lock` arguments were added.
  1261. * @since 5.3.0 The `supports` argument will now accept an array of arguments for a feature.
  1262. *
  1263. * @global array $wp_post_types List of post types.
  1264. *
  1265. * @param string $post_type Post type key. Must not exceed 20 characters and may
  1266. * only contain lowercase alphanumeric characters, dashes,
  1267. * and underscores. See sanitize_key().
  1268. * @param array|string $args {
  1269. * Array or string of arguments for registering a post type.
  1270. *
  1271. * @type string $label Name of the post type shown in the menu. Usually plural.
  1272. * Default is value of $labels['name'].
  1273. * @type string[] $labels An array of labels for this post type. If not set, post
  1274. * labels are inherited for non-hierarchical types and page
  1275. * labels for hierarchical ones. See get_post_type_labels() for a full
  1276. * list of supported labels.
  1277. * @type string $description A short descriptive summary of what the post type is.
  1278. * Default empty.
  1279. * @type bool $public Whether a post type is intended for use publicly either via
  1280. * the admin interface or by front-end users. While the default
  1281. * settings of $exclude_from_search, $publicly_queryable, $show_ui,
  1282. * and $show_in_nav_menus are inherited from public, each does not
  1283. * rely on this relationship and controls a very specific intention.
  1284. * Default false.
  1285. * @type bool $hierarchical Whether the post type is hierarchical (e.g. page). Default false.
  1286. * @type bool $exclude_from_search Whether to exclude posts with this post type from front end search
  1287. * results. Default is the opposite value of $public.
  1288. * @type bool $publicly_queryable Whether queries can be performed on the front end for the post type
  1289. * as part of parse_request(). Endpoints would include:
  1290. * * ?post_type={post_type_key}
  1291. * * ?{post_type_key}={single_post_slug}
  1292. * * ?{post_type_query_var}={single_post_slug}
  1293. * If not set, the default is inherited from $public.
  1294. * @type bool $show_ui Whether to generate and allow a UI for managing this post type in the
  1295. * admin. Default is value of $public.
  1296. * @type bool|string $show_in_menu Where to show the post type in the admin menu. To work, $show_ui
  1297. * must be true. If true, the post type is shown in its own top level
  1298. * menu. If false, no menu is shown. If a string of an existing top
  1299. * level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
  1300. * type will be placed as a sub-menu of that.
  1301. * Default is value of $show_ui.
  1302. * @type bool $show_in_nav_menus Makes this post type available for selection in navigation menus.
  1303. * Default is value of $public.
  1304. * @type bool $show_in_admin_bar Makes this post type available via the admin bar. Default is value
  1305. * of $show_in_menu.
  1306. * @type bool $show_in_rest Whether to include the post type in the REST API. Set this to true
  1307. * for the post type to be available in the block editor.
  1308. * @type string $rest_base To change the base url of REST API route. Default is $post_type.
  1309. * @type string $rest_controller_class REST API Controller class name. Default is 'WP_REST_Posts_Controller'.
  1310. * @type int $menu_position The position in the menu order the post type should appear. To work,
  1311. * $show_in_menu must be true. Default null (at the bottom).
  1312. * @type string $menu_icon The url to the icon to be used for this menu. Pass a base64-encoded
  1313. * SVG using a data URI, which will be colored to match the color scheme
  1314. * -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
  1315. * of a Dashicons helper class to use a font icon, e.g.
  1316. * 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
  1317. * so an icon can be added via CSS. Defaults to use the posts icon.
  1318. * @type string $capability_type The string to use to build the read, edit, and delete capabilities.
  1319. * May be passed as an array to allow for alternative plurals when using
  1320. * this argument as a base to construct the capabilities, e.g.
  1321. * array('story', 'stories'). Default 'post'.
  1322. * @type string[] $capabilities Array of capabilities for this post type. $capability_type is used
  1323. * as a base to construct capabilities by default.
  1324. * See get_post_type_capabilities().
  1325. * @type bool $map_meta_cap Whether to use the internal default meta capability handling.
  1326. * Default false.
  1327. * @type array $supports Core feature(s) the post type supports. Serves as an alias for calling
  1328. * add_post_type_support() directly. Core features include 'title',
  1329. * 'editor', 'comments', 'revisions', 'trackbacks', 'author', 'excerpt',
  1330. * 'page-attributes', 'thumbnail', 'custom-fields', and 'post-formats'.
  1331. * Additionally, the 'revisions' feature dictates whether the post type
  1332. * will store revisions, and the 'comments' feature dictates whether the
  1333. * comments count will show on the edit screen. A feature can also be
  1334. * specified as an array of arguments to provide additional information
  1335. * about supporting that feature.
  1336. * Example: `array( 'my_feature', array( 'field' => 'value' ) )`.
  1337. * Default is an array containing 'title' and 'editor'.
  1338. * @type callable $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
  1339. * edit form. Do remove_meta_box() and add_meta_box() calls in the
  1340. * callback. Default null.
  1341. * @type string[] $taxonomies An array of taxonomy identifiers that will be registered for the
  1342. * post type. Taxonomies can be registered later with register_taxonomy()
  1343. * or register_taxonomy_for_object_type().
  1344. * Default empty array.
  1345. * @type bool|string $has_archive Whether there should be post type archives, or if a string, the
  1346. * archive slug to use. Will generate the proper rewrite rules if
  1347. * $rewrite is enabled. Default false.
  1348. * @type bool|array $rewrite {
  1349. * Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
  1350. * Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
  1351. * passed with any of these keys:
  1352. *
  1353. * @type string $slug Customize the permastruct slug. Defaults to $post_type key.
  1354. * @type bool $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
  1355. * Default true.
  1356. * @type bool $feeds Whether the feed permastruct should be built for this post type.
  1357. * Default is value of $has_archive.
  1358. * @type bool $pages Whether the permastruct should provide for pagination. Default true.
  1359. * @type int $ep_mask Endpoint mask to assign. If not specified and permalink_epmask is set,
  1360. * inherits from $permalink_epmask. If not specified and permalink_epmask
  1361. * is not set, defaults to EP_PERMALINK.
  1362. * }
  1363. * @type string|bool $query_var Sets the query_var key for this post type. Defaults to $post_type
  1364. * key. If false, a post type cannot be loaded at
  1365. * ?{query_var}={post_slug}. If specified as a string, the query
  1366. * ?{query_var_string}={post_slug} will be valid.
  1367. * @type bool $can_export Whether to allow this post type to be exported. Default true.
  1368. * @type bool $delete_with_user Whether to delete posts of this type when deleting a user.
  1369. * * If true, posts of this type belonging to the user will be moved
  1370. * to Trash when the user is deleted.
  1371. * * If false, posts of this type belonging to the user will *not*
  1372. * be trashed or deleted.
  1373. * * If not set (the default), posts are trashed if post type supports
  1374. * the 'author' feature. Otherwise posts are not trashed or deleted.
  1375. * Default null.
  1376. * @type array $template Array of blocks to use as the default initial state for an editor
  1377. * session. Each item should be an array containing block name and
  1378. * optional attributes. Default empty array.
  1379. * @type string|false $template_lock Whether the block template should be locked if $template is set.
  1380. * * If set to 'all', the user is unable to insert new blocks,
  1381. * move existing blocks and delete blocks.
  1382. * * If set to 'insert', the user is able to move existing blocks
  1383. * but is unable to insert new blocks and delete blocks.
  1384. * Default false.
  1385. * @type bool $_builtin FOR INTERNAL USE ONLY! True if this post type is a native or
  1386. * "built-in" post_type. Default false.
  1387. * @type string $_edit_link FOR INTERNAL USE ONLY! URL segment to use for edit link of
  1388. * this post type. Default 'post.php?post=%d'.
  1389. * }
  1390. * @return WP_Post_Type|WP_Error The registered post type object on success,
  1391. * WP_Error object on failure.
  1392. */
  1393. function register_post_type( $post_type, $args = array() ) {
  1394. global $wp_post_types;
  1395. if ( ! is_array( $wp_post_types ) ) {
  1396. $wp_post_types = array();
  1397. }
  1398. // Sanitize post type name.
  1399. $post_type = sanitize_key( $post_type );
  1400. if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
  1401. _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2.0' );
  1402. return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
  1403. }
  1404. $post_type_object = new WP_Post_Type( $post_type, $args );
  1405. $post_type_object->add_supports();
  1406. $post_type_object->add_rewrite_rules();
  1407. $post_type_object->register_meta_boxes();
  1408. $wp_post_types[ $post_type ] = $post_type_object;
  1409. $post_type_object->add_hooks();
  1410. $post_type_object->register_taxonomies();
  1411. /**
  1412. * Fires after a post type is registered.
  1413. *
  1414. * @since 3.3.0
  1415. * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
  1416. *
  1417. * @param string $post_type Post type.
  1418. * @param WP_Post_Type $post_type_object Arguments used to register the post type.
  1419. */
  1420. do_action( 'registered_post_type', $post_type, $post_type_object );
  1421. return $post_type_object;
  1422. }
  1423. /**
  1424. * Unregisters a post type.
  1425. *
  1426. * Can not be used to unregister built-in post types.
  1427. *
  1428. * @since 4.5.0
  1429. *
  1430. * @global array $wp_post_types List of post types.
  1431. *
  1432. * @param string $post_type Post type to unregister.
  1433. * @return true|WP_Error True on success, WP_Error on failure or if the post type doesn't exist.
  1434. */
  1435. function unregister_post_type( $post_type ) {
  1436. global $wp_post_types;
  1437. if ( ! post_type_exists( $post_type ) ) {
  1438. return new WP_Error( 'invalid_post_type', __( 'Invalid post type.' ) );
  1439. }
  1440. $post_type_object = get_post_type_object( $post_type );
  1441. // Do not allow unregistering internal post types.
  1442. if ( $post_type_object->_builtin ) {
  1443. return new WP_Error( 'invalid_post_type', __( 'Unregistering a built-in post type is not allowed' ) );
  1444. }
  1445. $post_type_object->remove_supports();
  1446. $post_type_object->remove_rewrite_rules();
  1447. $post_type_object->unregister_meta_boxes();
  1448. $post_type_object->remove_hooks();
  1449. $post_type_object->unregister_taxonomies();
  1450. unset( $wp_post_types[ $post_type ] );
  1451. /**
  1452. * Fires after a post type was unregistered.
  1453. *
  1454. * @since 4.5.0
  1455. *
  1456. * @param string $post_type Post type key.
  1457. */
  1458. do_action( 'unregistered_post_type', $post_type );
  1459. return true;
  1460. }
  1461. /**
  1462. * Build an object with all post type capabilities out of a post type object
  1463. *
  1464. * Post type capabilities use the 'capability_type' argument as a base, if the
  1465. * capability is not set in the 'capabilities' argument array or if the
  1466. * 'capabilities' argument is not supplied.
  1467. *
  1468. * The capability_type argument can optionally be registered as an array, with
  1469. * the first value being singular and the second plural, e.g. array('story, 'stories')
  1470. * Otherwise, an 's' will be added to the value for the plural form. After
  1471. * registration, capability_type will always be a string of the singular value.
  1472. *
  1473. * By default, eight keys are accepted as part of the capabilities array:
  1474. *
  1475. * - edit_post, read_post, and delete_post are meta capabilities, which are then
  1476. * generally mapped to corresponding primitive capabilities depending on the
  1477. * context, which would be the post being edited/read/deleted and the user or
  1478. * role being checked. Thus these capabilities would generally not be granted
  1479. * directly to users or roles.
  1480. *
  1481. * - edit_posts - Controls whether objects of this post type can be edited.
  1482. * - edit_others_posts - Controls whether objects of this type owned by other users
  1483. * can be edited. If the post type does not support an author, then this will
  1484. * behave like edit_posts.
  1485. * - delete_posts - Controls whether objects of this post type can be deleted.
  1486. * - publish_posts - Controls publishing objects of this post type.
  1487. * - read_private_posts - Controls whether private objects can be read.
  1488. *
  1489. * These five primitive capabilities are checked in core in various locations.
  1490. * There are also six other primitive capabilities which are not referenced
  1491. * directly in core, except in map_meta_cap(), which takes the three aforementioned
  1492. * meta capabilities and translates them into one or more primitive capabilities
  1493. * that must then be checked against the user or role, depending on the context.
  1494. *
  1495. * - read - Controls whether objects of this post type can be read.
  1496. * - delete_private_posts - Controls whether private objects can be deleted.
  1497. * - delete_published_posts - Controls whether published objects can be deleted.
  1498. * - delete_others_posts - Controls whether objects owned by other users can be
  1499. * can be deleted. If the post type does not support an author, then this will
  1500. * behave like delete_posts.
  1501. * - edit_private_posts - Controls whether private objects can be edited.
  1502. * - edit_published_posts - Controls whether published objects can be edited.
  1503. *
  1504. * These additional capabilities are only used in map_meta_cap(). Thus, they are
  1505. * only assigned by default if the post type is registered with the 'map_meta_cap'
  1506. * argument set to true (default is false).
  1507. *
  1508. * @since 3.0.0
  1509. * @since 5.4.0 'delete_posts' is included in default capabilities.
  1510. *
  1511. * @see register_post_type()
  1512. * @see map_meta_cap()
  1513. *
  1514. * @param object $args Post type registration arguments.
  1515. * @return object Object with all the capabilities as member variables.
  1516. */
  1517. function get_post_type_capabilities( $args ) {
  1518. if ( ! is_array( $args->capability_type ) ) {
  1519. $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
  1520. }
  1521. // Singular base for meta capabilities, plural base for primitive capabilities.
  1522. list( $singular_base, $plural_base ) = $args->capability_type;
  1523. $default_capabilities = array(
  1524. // Meta capabilities.
  1525. 'edit_post' => 'edit_' . $singular_base,
  1526. 'read_post' => 'read_' . $singular_base,
  1527. 'delete_post' => 'delete_' . $singular_base,
  1528. // Primitive capabilities used outside of map_meta_cap():
  1529. 'edit_posts' => 'edit_' . $plural_base,
  1530. 'edit_others_posts' => 'edit_others_' . $plural_base,
  1531. 'delete_posts' => 'delete_' . $plural_base,
  1532. 'publish_posts' => 'publish_' . $plural_base,
  1533. 'read_private_posts' => 'read_private_' . $plural_base,
  1534. );
  1535. // Primitive capabilities used within map_meta_cap():
  1536. if ( $args->map_meta_cap ) {
  1537. $default_capabilities_for_mapping = array(
  1538. 'read' => 'read',
  1539. 'delete_private_posts' => 'delete_private_' . $plural_base,
  1540. 'delete_published_posts' => 'delete_published_' . $plural_base,
  1541. 'delete_others_posts' => 'delete_others_' . $plural_base,
  1542. 'edit_private_posts' => 'edit_private_' . $plural_base,
  1543. 'edit_published_posts' => 'edit_published_' . $plural_base,
  1544. );
  1545. $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
  1546. }
  1547. $capabilities = array_merge( $default_capabilities, $args->capabilities );
  1548. // Post creation capability simply maps to edit_posts by default:
  1549. if ( ! isset( $capabilities['create_posts'] ) ) {
  1550. $capabilities['create_posts'] = $capabilities['edit_posts'];
  1551. }
  1552. // Remember meta capabilities for future reference.
  1553. if ( $args->map_meta_cap ) {
  1554. _post_type_meta_capabilities( $capabilities );
  1555. }
  1556. return (object) $capabilities;
  1557. }
  1558. /**
  1559. * Store or return a list of post type meta caps for map_meta_cap().
  1560. *
  1561. * @since 3.1.0
  1562. * @access private
  1563. *
  1564. * @global array $post_type_meta_caps Used to store meta capabilities.
  1565. *
  1566. * @param string[] $capabilities Post type meta capabilities.
  1567. */
  1568. function _post_type_meta_capabilities( $capabilities = null ) {
  1569. global $post_type_meta_caps;
  1570. foreach ( $capabilities as $core => $custom ) {
  1571. if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ), true ) ) {
  1572. $post_type_meta_caps[ $custom ] = $core;
  1573. }
  1574. }
  1575. }
  1576. /**
  1577. * Builds an object with all post type labels out of a post type object.
  1578. *
  1579. * Accepted keys of the label array in the post type object:
  1580. *
  1581. * - `name` - General name for the post type, usually plural. The same and overridden
  1582. * by `$post_type_object->label`. Default is 'Posts' / 'Pages'.
  1583. * - `singular_name` - Name for one object of this post type. Default is 'Post' / 'Page'.
  1584. * - `add_new` - Default is 'Add New' for both hierarchical and non-hierarchical types.
  1585. * When internationalizing this string, please use a {@link https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/#disambiguation-by-context gettext context}
  1586. * matching your post type. Example: `_x( 'Add New', 'product', 'textdomain' );`.
  1587. * - `add_new_item` - Label for adding a new singular item. Default is 'Add New Post' / 'Add New Page'.
  1588. * - `edit_item` - Label for editing a singular item. Default is 'Edit Post' / 'Edit Page'.
  1589. * - `new_item` - Label for the new item page title. Default is 'New Post' / 'New Page'.
  1590. * - `view_item` - Label for viewing a singular item. Default is 'View Post' / 'View Page'.
  1591. * - `view_items` - Label for viewing post type archives. Default is 'View Posts' / 'View Pages'.
  1592. * - `search_items` - Label for searching plural items. Default is 'Search Posts' / 'Search Pages'.
  1593. * - `not_found` - Label used when no items are found. Default is 'No posts found' / 'No pages found'.
  1594. * - `not_found_in_trash` - Label used when no items are in the Trash. Default is 'No posts found in Trash' /
  1595. * 'No pages found in Trash'.
  1596. * - `parent_item_colon` - Label used to prefix parents of hierarchical items. Not used on non-hierarchical
  1597. * post types. Default is 'Parent Page:'.
  1598. * - `all_items` - Label to signify all items in a submenu link. Default is 'All Posts' / 'All Pages'.
  1599. * - `archives` - Label for archives in nav menus. Default is 'Post Archives' / 'Page Archives'.
  1600. * - `attributes` - Label for the attributes meta box. Default is 'Post Attributes' / 'Page Attributes'.
  1601. * - `insert_into_item` - Label for the media frame button. Default is 'Insert into post' / 'Insert into page'.
  1602. * - `uploaded_to_this_item` - Label for the media frame filter. Default is 'Uploaded to this post' /
  1603. * 'Uploaded to this page'.
  1604. * - `featured_image` - Label for the featured image meta box title. Default is 'Featured image'.
  1605. * - `set_featured_image` - Label for setting the featured image. Default is 'Set featured image'.
  1606. * - `remove_featured_image` - Label for removing the featured image. Default is 'Remove featured image'.
  1607. * - `use_featured_image` - Label in the media frame for using a featured image. Default is 'Use as featured image'.
  1608. * - `menu_name` - Label for the menu name. Default is the same as `name`.
  1609. * - `filter_items_list` - Label for the table views hidden heading. Default is 'Filter posts list' /
  1610. * 'Filter pages list'.
  1611. * - `filter_by_date` - Label for the date filter in list tables. Default is 'Filter by date'.
  1612. * - `items_list_navigation` - Label for the table pagination hidden heading. Default is 'Posts list navigation' /
  1613. * 'Pages list navigation'.
  1614. * - `items_list` - Label for the table hidden heading. Default is 'Posts list' / 'Pages list'.
  1615. * - `item_published` - Label used when an item is published. Default is 'Post published.' / 'Page published.'
  1616. * - `item_published_privately` - Label used when an item is published with private visibility.
  1617. * Default is 'Post published privately.' / 'Page published privately.'
  1618. * - `item_reverted_to_draft` - Label used when an item is switched to a draft.
  1619. * Default is 'Post reverted to draft.' / 'Page reverted to draft.'
  1620. * - `item_scheduled` - Label used when an item is scheduled for publishing. Default is 'Post scheduled.' /
  1621. * 'Page scheduled.'
  1622. * - `item_updated` - Label used when an item is updated. Default is 'Post updated.' / 'Page updated.'
  1623. * - `item_link` - Title for a navigation link block variation. Default is 'Post Link' / 'Page Link'.
  1624. * - `item_link_description` - Description for a navigation link block variation. Default is 'A link to a post.' /
  1625. * 'A link to a page.'
  1626. *
  1627. * Above, the first default value is for non-hierarchical post types (like posts)
  1628. * and the second one is for hierarchical post types (like pages).
  1629. *
  1630. * Note: To set labels used in post type admin notices, see the {@see 'post_updated_messages'} filter.
  1631. *
  1632. * @since 3.0.0
  1633. * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
  1634. * and `use_featured_image` labels.
  1635. * @since 4.4.0 Added the `archives`, `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
  1636. * `items_list_navigation`, and `items_list` labels.
  1637. * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
  1638. * @since 4.7.0 Added the `view_items` and `attributes` labels.
  1639. * @since 5.0.0 Added the `item_published`, `item_published_privately`, `item_reverted_to_draft`,
  1640. * `item_scheduled`, and `item_updated` labels.
  1641. * @since 5.7.0 Added the `filter_by_date` label.
  1642. * @since 5.8.0 Added the `item_link` and `item_link_description` labels.
  1643. *
  1644. * @access private
  1645. *
  1646. * @param object|WP_Post_Type $post_type_object Post type object.
  1647. * @return object Object with all the labels as member variables.
  1648. */
  1649. function get_post_type_labels( $post_type_object ) {
  1650. $nohier_vs_hier_defaults = array(
  1651. 'name' => array( _x( 'Posts', 'post type general name' ), _x( 'Pages', 'post type general name' ) ),
  1652. 'singular_name' => array( _x( 'Post', 'post type singular name' ), _x( 'Page', 'post type singular name' ) ),
  1653. 'add_new' => array( _x( 'Add New', 'post' ), _x( 'Add New', 'page' ) ),
  1654. 'add_new_item' => array( __( 'Add New Post' ), __( 'Add New Page' ) ),
  1655. 'edit_item' => array( __( 'Edit Post' ), __( 'Edit Page' ) ),
  1656. 'new_item' => array( __( 'New Post' ), __( 'New Page' ) ),
  1657. 'view_item' => array( __( 'View Post' ), __( 'View Page' ) ),
  1658. 'view_items' => array( __( 'View Posts' ), __( 'View Pages' ) ),
  1659. 'search_items' => array( __( 'Search Posts' ), __( 'Search Pages' ) ),
  1660. 'not_found' => array( __( 'No posts found.' ), __( 'No pages found.' ) ),
  1661. 'not_found_in_trash' => array( __( 'No posts found in Trash.' ), __( 'No pages found in Trash.' ) ),
  1662. 'parent_item_colon' => array( null, __( 'Parent Page:' ) ),
  1663. 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
  1664. 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
  1665. 'attributes' => array( __( 'Post Attributes' ), __( 'Page Attributes' ) ),
  1666. 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
  1667. 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
  1668. 'featured_image' => array( _x( 'Featured image', 'post' ), _x( 'Featured image', 'page' ) ),
  1669. 'set_featured_image' => array( _x( 'Set featured image', 'post' ), _x( 'Set featured image', 'page' ) ),
  1670. 'remove_featured_image' => array( _x( 'Remove featured image', 'post' ), _x( 'Remove featured image', 'page' ) ),
  1671. 'use_featured_image' => array( _x( 'Use as featured image', 'post' ), _x( 'Use as featured image', 'page' ) ),
  1672. 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
  1673. 'filter_by_date' => array( __( 'Filter by date' ), __( 'Filter by date' ) ),
  1674. 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
  1675. 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
  1676. 'item_published' => array( __( 'Post published.' ), __( 'Page published.' ) ),
  1677. 'item_published_privately' => array( __( 'Post published privately.' ), __( 'Page published privately.' ) ),
  1678. 'item_reverted_to_draft' => array( __( 'Post reverted to draft.' ), __( 'Page reverted to draft.' ) ),
  1679. 'item_scheduled' => array( __( 'Post scheduled.' ), __( 'Page scheduled.' ) ),
  1680. 'item_updated' => array( __( 'Post updated.' ), __( 'Page updated.' ) ),
  1681. 'item_link' => array(
  1682. _x( 'Post Link', 'navigation link block title' ),
  1683. _x( 'Page Link', 'navigation link block title' ),
  1684. ),
  1685. 'item_link_description' => array(
  1686. _x( 'A link to a post.', 'navigation link block description' ),
  1687. _x( 'A link to a page.', 'navigation link block description' ),
  1688. ),
  1689. );
  1690. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  1691. $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
  1692. $post_type = $post_type_object->name;
  1693. $default_labels = clone $labels;
  1694. /**
  1695. * Filters the labels of a specific post type.
  1696. *
  1697. * The dynamic portion of the hook name, `$post_type`, refers to
  1698. * the post type slug.
  1699. *
  1700. * Possible hook names include:
  1701. *
  1702. * - `post_type_labels_post`
  1703. * - `post_type_labels_page`
  1704. * - `post_type_labels_attachment`
  1705. *
  1706. * @since 3.5.0
  1707. *
  1708. * @see get_post_type_labels() for the full list of labels.
  1709. *
  1710. * @param object $labels Object with labels for the post type as member variables.
  1711. */
  1712. $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
  1713. // Ensure that the filtered labels contain all required default values.
  1714. $labels = (object) array_merge( (array) $default_labels, (array) $labels );
  1715. return $labels;
  1716. }
  1717. /**
  1718. * Build an object with custom-something object (post type, taxonomy) labels
  1719. * out of a custom-something object
  1720. *
  1721. * @since 3.0.0
  1722. * @access private
  1723. *
  1724. * @param object $object A custom-something object.
  1725. * @param array $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
  1726. * @return object Object containing labels for the given custom-something object.
  1727. */
  1728. function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
  1729. $object->labels = (array) $object->labels;
  1730. if ( isset( $object->label ) && empty( $object->labels['name'] ) ) {
  1731. $object->labels['name'] = $object->label;
  1732. }
  1733. if ( ! isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) ) {
  1734. $object->labels['singular_name'] = $object->labels['name'];
  1735. }
  1736. if ( ! isset( $object->labels['name_admin_bar'] ) ) {
  1737. $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
  1738. }
  1739. if ( ! isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) ) {
  1740. $object->labels['menu_name'] = $object->labels['name'];
  1741. }
  1742. if ( ! isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) ) {
  1743. $object->labels['all_items'] = $object->labels['menu_name'];
  1744. }
  1745. if ( ! isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
  1746. $object->labels['archives'] = $object->labels['all_items'];
  1747. }
  1748. $defaults = array();
  1749. foreach ( $nohier_vs_hier_defaults as $key => $value ) {
  1750. $defaults[ $key ] = $object->hierarchical ? $value[1] : $value[0];
  1751. }
  1752. $labels = array_merge( $defaults, $object->labels );
  1753. $object->labels = (object) $object->labels;
  1754. return (object) $labels;
  1755. }
  1756. /**
  1757. * Add submenus for post types.
  1758. *
  1759. * @access private
  1760. * @since 3.1.0
  1761. */
  1762. function _add_post_type_submenus() {
  1763. foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
  1764. $ptype_obj = get_post_type_object( $ptype );
  1765. // Sub-menus only.
  1766. if ( ! $ptype_obj->show_in_menu || true === $ptype_obj->show_in_menu ) {
  1767. continue;
  1768. }
  1769. add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
  1770. }
  1771. }
  1772. /**
  1773. * Registers support of certain features for a post type.
  1774. *
  1775. * All core features are directly associated with a functional area of the edit
  1776. * screen, such as the editor or a meta box. Features include: 'title', 'editor',
  1777. * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
  1778. * 'thumbnail', 'custom-fields', and 'post-formats'.
  1779. *
  1780. * Additionally, the 'revisions' feature dictates whether the post type will
  1781. * store revisions, and the 'comments' feature dictates whether the comments
  1782. * count will show on the edit screen.
  1783. *
  1784. * A third, optional parameter can also be passed along with a feature to provide
  1785. * additional information about supporting that feature.
  1786. *
  1787. * Example usage:
  1788. *
  1789. * add_post_type_support( 'my_post_type', 'comments' );
  1790. * add_post_type_support( 'my_post_type', array(
  1791. * 'author', 'excerpt',
  1792. * ) );
  1793. * add_post_type_support( 'my_post_type', 'my_feature', array(
  1794. * 'field' => 'value',
  1795. * ) );
  1796. *
  1797. * @since 3.0.0
  1798. * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
  1799. * by adding it to the function signature.
  1800. *
  1801. * @global array $_wp_post_type_features
  1802. *
  1803. * @param string $post_type The post type for which to add the feature.
  1804. * @param string|array $feature The feature being added, accepts an array of
  1805. * feature strings or a single string.
  1806. * @param mixed ...$args Optional extra arguments to pass along with certain features.
  1807. */
  1808. function add_post_type_support( $post_type, $feature, ...$args ) {
  1809. global $_wp_post_type_features;
  1810. $features = (array) $feature;
  1811. foreach ( $features as $feature ) {
  1812. if ( $args ) {
  1813. $_wp_post_type_features[ $post_type ][ $feature ] = $args;
  1814. } else {
  1815. $_wp_post_type_features[ $post_type ][ $feature ] = true;
  1816. }
  1817. }
  1818. }
  1819. /**
  1820. * Remove support for a feature from a post type.
  1821. *
  1822. * @since 3.0.0
  1823. *
  1824. * @global array $_wp_post_type_features
  1825. *
  1826. * @param string $post_type The post type for which to remove the feature.
  1827. * @param string $feature The feature being removed.
  1828. */
  1829. function remove_post_type_support( $post_type, $feature ) {
  1830. global $_wp_post_type_features;
  1831. unset( $_wp_post_type_features[ $post_type ][ $feature ] );
  1832. }
  1833. /**
  1834. * Get all the post type features
  1835. *
  1836. * @since 3.4.0
  1837. *
  1838. * @global array $_wp_post_type_features
  1839. *
  1840. * @param string $post_type The post type.
  1841. * @return array Post type supports list.
  1842. */
  1843. function get_all_post_type_supports( $post_type ) {
  1844. global $_wp_post_type_features;
  1845. if ( isset( $_wp_post_type_features[ $post_type ] ) ) {
  1846. return $_wp_post_type_features[ $post_type ];
  1847. }
  1848. return array();
  1849. }
  1850. /**
  1851. * Check a post type's support for a given feature.
  1852. *
  1853. * @since 3.0.0
  1854. *
  1855. * @global array $_wp_post_type_features
  1856. *
  1857. * @param string $post_type The post type being checked.
  1858. * @param string $feature The feature being checked.
  1859. * @return bool Whether the post type supports the given feature.
  1860. */
  1861. function post_type_supports( $post_type, $feature ) {
  1862. global $_wp_post_type_features;
  1863. return ( isset( $_wp_post_type_features[ $post_type ][ $feature ] ) );
  1864. }
  1865. /**
  1866. * Retrieves a list of post type names that support a specific feature.
  1867. *
  1868. * @since 4.5.0
  1869. *
  1870. * @global array $_wp_post_type_features Post type features
  1871. *
  1872. * @param array|string $feature Single feature or an array of features the post types should support.
  1873. * @param string $operator Optional. The logical operation to perform. 'or' means
  1874. * only one element from the array needs to match; 'and'
  1875. * means all elements must match; 'not' means no elements may
  1876. * match. Default 'and'.
  1877. * @return string[] A list of post type names.
  1878. */
  1879. function get_post_types_by_support( $feature, $operator = 'and' ) {
  1880. global $_wp_post_type_features;
  1881. $features = array_fill_keys( (array) $feature, true );
  1882. return array_keys( wp_filter_object_list( $_wp_post_type_features, $features, $operator ) );
  1883. }
  1884. /**
  1885. * Update the post type for the post ID.
  1886. *
  1887. * The page or post cache will be cleaned for the post ID.
  1888. *
  1889. * @since 2.5.0
  1890. *
  1891. * @global wpdb $wpdb WordPress database abstraction object.
  1892. *
  1893. * @param int $post_id Optional. Post ID to change post type. Default 0.
  1894. * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
  1895. * name a few. Default 'post'.
  1896. * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
  1897. */
  1898. function set_post_type( $post_id = 0, $post_type = 'post' ) {
  1899. global $wpdb;
  1900. $post_type = sanitize_post_field( 'post_type', $post_type, $post_id, 'db' );
  1901. $return = $wpdb->update( $wpdb->posts, array( 'post_type' => $post_type ), array( 'ID' => $post_id ) );
  1902. clean_post_cache( $post_id );
  1903. return $return;
  1904. }
  1905. /**
  1906. * Determines whether a post type is considered "viewable".
  1907. *
  1908. * For built-in post types such as posts and pages, the 'public' value will be evaluated.
  1909. * For all others, the 'publicly_queryable' value will be used.
  1910. *
  1911. * @since 4.4.0
  1912. * @since 4.5.0 Added the ability to pass a post type name in addition to object.
  1913. * @since 4.6.0 Converted the `$post_type` parameter to accept a `WP_Post_Type` object.
  1914. *
  1915. * @param string|WP_Post_Type $post_type Post type name or object.
  1916. * @return bool Whether the post type should be considered viewable.
  1917. */
  1918. function is_post_type_viewable( $post_type ) {
  1919. if ( is_scalar( $post_type ) ) {
  1920. $post_type = get_post_type_object( $post_type );
  1921. if ( ! $post_type ) {
  1922. return false;
  1923. }
  1924. }
  1925. if ( ! is_object( $post_type ) ) {
  1926. return false;
  1927. }
  1928. return $post_type->publicly_queryable || ( $post_type->_builtin && $post_type->public );
  1929. }
  1930. /**
  1931. * Determine whether a post status is considered "viewable".
  1932. *
  1933. * For built-in post statuses such as publish and private, the 'public' value will be evaluted.
  1934. * For all others, the 'publicly_queryable' value will be used.
  1935. *
  1936. * @since 5.7.0
  1937. *
  1938. * @param string|stdClass $post_status Post status name or object.
  1939. * @return bool Whether the post status should be considered viewable.
  1940. */
  1941. function is_post_status_viewable( $post_status ) {
  1942. if ( is_scalar( $post_status ) ) {
  1943. $post_status = get_post_status_object( $post_status );
  1944. if ( ! $post_status ) {
  1945. return false;
  1946. }
  1947. }
  1948. if (
  1949. ! is_object( $post_status ) ||
  1950. $post_status->internal ||
  1951. $post_status->protected
  1952. ) {
  1953. return false;
  1954. }
  1955. return $post_status->publicly_queryable || ( $post_status->_builtin && $post_status->public );
  1956. }
  1957. /**
  1958. * Determine whether a post is publicly viewable.
  1959. *
  1960. * Posts are considered publicly viewable if both the post status and post type
  1961. * are viewable.
  1962. *
  1963. * @since 5.7.0
  1964. *
  1965. * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
  1966. * @return bool Whether the post is publicly viewable.
  1967. */
  1968. function is_post_publicly_viewable( $post = null ) {
  1969. $post = get_post( $post );
  1970. if ( ! $post ) {
  1971. return false;
  1972. }
  1973. $post_type = get_post_type( $post );
  1974. $post_status = get_post_status( $post );
  1975. return is_post_type_viewable( $post_type ) && is_post_status_viewable( $post_status );
  1976. }
  1977. /**
  1978. * Retrieves an array of the latest posts, or posts matching the given criteria.
  1979. *
  1980. * For more information on the accepted arguments, see the
  1981. * {@link https://developer.wordpress.org/reference/classes/wp_query/
  1982. * WP_Query} documentation in the Developer Handbook.
  1983. *
  1984. * The `$ignore_sticky_posts` and `$no_found_rows` arguments are ignored by
  1985. * this function and both are set to `true`.
  1986. *
  1987. * The defaults are as follows:
  1988. *
  1989. * @since 1.2.0
  1990. *
  1991. * @see WP_Query
  1992. * @see WP_Query::parse_query()
  1993. *
  1994. * @param array $args {
  1995. * Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
  1996. * available arguments.
  1997. *
  1998. * @type int $numberposts Total number of posts to retrieve. Is an alias of `$posts_per_page`
  1999. * in WP_Query. Accepts -1 for all. Default 5.
  2000. * @type int|string $category Category ID or comma-separated list of IDs (this or any children).
  2001. * Is an alias of `$cat` in WP_Query. Default 0.
  2002. * @type int[] $include An array of post IDs to retrieve, sticky posts will be included.
  2003. * Is an alias of `$post__in` in WP_Query. Default empty array.
  2004. * @type int[] $exclude An array of post IDs not to retrieve. Default empty array.
  2005. * @type bool $suppress_filters Whether to suppress filters. Default true.
  2006. * }
  2007. * @return WP_Post[]|int[] Array of post objects or post IDs.
  2008. */
  2009. function get_posts( $args = null ) {
  2010. $defaults = array(
  2011. 'numberposts' => 5,
  2012. 'category' => 0,
  2013. 'orderby' => 'date',
  2014. 'order' => 'DESC',
  2015. 'include' => array(),
  2016. 'exclude' => array(),
  2017. 'meta_key' => '',
  2018. 'meta_value' => '',
  2019. 'post_type' => 'post',
  2020. 'suppress_filters' => true,
  2021. );
  2022. $parsed_args = wp_parse_args( $args, $defaults );
  2023. if ( empty( $parsed_args['post_status'] ) ) {
  2024. $parsed_args['post_status'] = ( 'attachment' === $parsed_args['post_type'] ) ? 'inherit' : 'publish';
  2025. }
  2026. if ( ! empty( $parsed_args['numberposts'] ) && empty( $parsed_args['posts_per_page'] ) ) {
  2027. $parsed_args['posts_per_page'] = $parsed_args['numberposts'];
  2028. }
  2029. if ( ! empty( $parsed_args['category'] ) ) {
  2030. $parsed_args['cat'] = $parsed_args['category'];
  2031. }
  2032. if ( ! empty( $parsed_args['include'] ) ) {
  2033. $incposts = wp_parse_id_list( $parsed_args['include'] );
  2034. $parsed_args['posts_per_page'] = count( $incposts ); // Only the number of posts included.
  2035. $parsed_args['post__in'] = $incposts;
  2036. } elseif ( ! empty( $parsed_args['exclude'] ) ) {
  2037. $parsed_args['post__not_in'] = wp_parse_id_list( $parsed_args['exclude'] );
  2038. }
  2039. $parsed_args['ignore_sticky_posts'] = true;
  2040. $parsed_args['no_found_rows'] = true;
  2041. $get_posts = new WP_Query;
  2042. return $get_posts->query( $parsed_args );
  2043. }
  2044. //
  2045. // Post meta functions.
  2046. //
  2047. /**
  2048. * Adds a meta field to the given post.
  2049. *
  2050. * Post meta data is called "Custom Fields" on the Administration Screen.
  2051. *
  2052. * @since 1.5.0
  2053. *
  2054. * @param int $post_id Post ID.
  2055. * @param string $meta_key Metadata name.
  2056. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  2057. * @param bool $unique Optional. Whether the same key should not be added.
  2058. * Default false.
  2059. * @return int|false Meta ID on success, false on failure.
  2060. */
  2061. function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
  2062. // Make sure meta is added to the post, not a revision.
  2063. $the_post = wp_is_post_revision( $post_id );
  2064. if ( $the_post ) {
  2065. $post_id = $the_post;
  2066. }
  2067. return add_metadata( 'post', $post_id, $meta_key, $meta_value, $unique );
  2068. }
  2069. /**
  2070. * Deletes a post meta field for the given post ID.
  2071. *
  2072. * You can match based on the key, or key and value. Removing based on key and
  2073. * value, will keep from removing duplicate metadata with the same key. It also
  2074. * allows removing all metadata matching the key, if needed.
  2075. *
  2076. * @since 1.5.0
  2077. *
  2078. * @param int $post_id Post ID.
  2079. * @param string $meta_key Metadata name.
  2080. * @param mixed $meta_value Optional. Metadata value. If provided,
  2081. * rows will only be removed that match the value.
  2082. * Must be serializable if non-scalar. Default empty.
  2083. * @return bool True on success, false on failure.
  2084. */
  2085. function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
  2086. // Make sure meta is added to the post, not a revision.
  2087. $the_post = wp_is_post_revision( $post_id );
  2088. if ( $the_post ) {
  2089. $post_id = $the_post;
  2090. }
  2091. return delete_metadata( 'post', $post_id, $meta_key, $meta_value );
  2092. }
  2093. /**
  2094. * Retrieves a post meta field for the given post ID.
  2095. *
  2096. * @since 1.5.0
  2097. *
  2098. * @param int $post_id Post ID.
  2099. * @param string $key Optional. The meta key to retrieve. By default,
  2100. * returns data for all keys. Default empty.
  2101. * @param bool $single Optional. Whether to return a single value.
  2102. * This parameter has no effect if `$key` is not specified.
  2103. * Default false.
  2104. * @return mixed An array of values if `$single` is false.
  2105. * The value of the meta field if `$single` is true.
  2106. * False for an invalid `$post_id` (non-numeric, zero, or negative value).
  2107. * An empty string if a valid but non-existing post ID is passed.
  2108. */
  2109. function get_post_meta( $post_id, $key = '', $single = false ) {
  2110. return get_metadata( 'post', $post_id, $key, $single );
  2111. }
  2112. /**
  2113. * Updates a post meta field based on the given post ID.
  2114. *
  2115. * Use the `$prev_value` parameter to differentiate between meta fields with the
  2116. * same key and post ID.
  2117. *
  2118. * If the meta field for the post does not exist, it will be added and its ID returned.
  2119. *
  2120. * Can be used in place of add_post_meta().
  2121. *
  2122. * @since 1.5.0
  2123. *
  2124. * @param int $post_id Post ID.
  2125. * @param string $meta_key Metadata key.
  2126. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  2127. * @param mixed $prev_value Optional. Previous value to check before updating.
  2128. * If specified, only update existing metadata entries with
  2129. * this value. Otherwise, update all entries. Default empty.
  2130. * @return int|bool Meta ID if the key didn't exist, true on successful update,
  2131. * false on failure or if the value passed to the function
  2132. * is the same as the one that is already in the database.
  2133. */
  2134. function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
  2135. // Make sure meta is added to the post, not a revision.
  2136. $the_post = wp_is_post_revision( $post_id );
  2137. if ( $the_post ) {
  2138. $post_id = $the_post;
  2139. }
  2140. return update_metadata( 'post', $post_id, $meta_key, $meta_value, $prev_value );
  2141. }
  2142. /**
  2143. * Deletes everything from post meta matching the given meta key.
  2144. *
  2145. * @since 2.3.0
  2146. *
  2147. * @param string $post_meta_key Key to search for when deleting.
  2148. * @return bool Whether the post meta key was deleted from the database.
  2149. */
  2150. function delete_post_meta_by_key( $post_meta_key ) {
  2151. return delete_metadata( 'post', null, $post_meta_key, '', true );
  2152. }
  2153. /**
  2154. * Registers a meta key for posts.
  2155. *
  2156. * @since 4.9.8
  2157. *
  2158. * @param string $post_type Post type to register a meta key for. Pass an empty string
  2159. * to register the meta key across all existing post types.
  2160. * @param string $meta_key The meta key to register.
  2161. * @param array $args Data used to describe the meta key when registered. See
  2162. * {@see register_meta()} for a list of supported arguments.
  2163. * @return bool True if the meta key was successfully registered, false if not.
  2164. */
  2165. function register_post_meta( $post_type, $meta_key, array $args ) {
  2166. $args['object_subtype'] = $post_type;
  2167. return register_meta( 'post', $meta_key, $args );
  2168. }
  2169. /**
  2170. * Unregisters a meta key for posts.
  2171. *
  2172. * @since 4.9.8
  2173. *
  2174. * @param string $post_type Post type the meta key is currently registered for. Pass
  2175. * an empty string if the meta key is registered across all
  2176. * existing post types.
  2177. * @param string $meta_key The meta key to unregister.
  2178. * @return bool True on success, false if the meta key was not previously registered.
  2179. */
  2180. function unregister_post_meta( $post_type, $meta_key ) {
  2181. return unregister_meta_key( 'post', $meta_key, $post_type );
  2182. }
  2183. /**
  2184. * Retrieve post meta fields, based on post ID.
  2185. *
  2186. * The post meta fields are retrieved from the cache where possible,
  2187. * so the function is optimized to be called more than once.
  2188. *
  2189. * @since 1.2.0
  2190. *
  2191. * @param int $post_id Optional. Post ID. Default is ID of the global $post.
  2192. * @return array Post meta for the given post.
  2193. */
  2194. function get_post_custom( $post_id = 0 ) {
  2195. $post_id = absint( $post_id );
  2196. if ( ! $post_id ) {
  2197. $post_id = get_the_ID();
  2198. }
  2199. return get_post_meta( $post_id );
  2200. }
  2201. /**
  2202. * Retrieve meta field names for a post.
  2203. *
  2204. * If there are no meta fields, then nothing (null) will be returned.
  2205. *
  2206. * @since 1.2.0
  2207. *
  2208. * @param int $post_id Optional. Post ID. Default is ID of the global $post.
  2209. * @return array|void Array of the keys, if retrieved.
  2210. */
  2211. function get_post_custom_keys( $post_id = 0 ) {
  2212. $custom = get_post_custom( $post_id );
  2213. if ( ! is_array( $custom ) ) {
  2214. return;
  2215. }
  2216. $keys = array_keys( $custom );
  2217. if ( $keys ) {
  2218. return $keys;
  2219. }
  2220. }
  2221. /**
  2222. * Retrieve values for a custom post field.
  2223. *
  2224. * The parameters must not be considered optional. All of the post meta fields
  2225. * will be retrieved and only the meta field key values returned.
  2226. *
  2227. * @since 1.2.0
  2228. *
  2229. * @param string $key Optional. Meta field key. Default empty.
  2230. * @param int $post_id Optional. Post ID. Default is ID of the global $post.
  2231. * @return array|null Meta field values.
  2232. */
  2233. function get_post_custom_values( $key = '', $post_id = 0 ) {
  2234. if ( ! $key ) {
  2235. return null;
  2236. }
  2237. $custom = get_post_custom( $post_id );
  2238. return isset( $custom[ $key ] ) ? $custom[ $key ] : null;
  2239. }
  2240. /**
  2241. * Determines whether a post is sticky.
  2242. *
  2243. * Sticky posts should remain at the top of The Loop. If the post ID is not
  2244. * given, then The Loop ID for the current post will be used.
  2245. *
  2246. * For more information on this and similar theme functions, check out
  2247. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  2248. * Conditional Tags} article in the Theme Developer Handbook.
  2249. *
  2250. * @since 2.7.0
  2251. *
  2252. * @param int $post_id Optional. Post ID. Default is ID of the global $post.
  2253. * @return bool Whether post is sticky.
  2254. */
  2255. function is_sticky( $post_id = 0 ) {
  2256. $post_id = absint( $post_id );
  2257. if ( ! $post_id ) {
  2258. $post_id = get_the_ID();
  2259. }
  2260. $stickies = get_option( 'sticky_posts' );
  2261. if ( is_array( $stickies ) ) {
  2262. $stickies = array_map( 'intval', $stickies );
  2263. $is_sticky = in_array( $post_id, $stickies, true );
  2264. } else {
  2265. $is_sticky = false;
  2266. }
  2267. /**
  2268. * Filters whether a post is sticky.
  2269. *
  2270. * @since 5.3.0
  2271. *
  2272. * @param bool $is_sticky Whether a post is sticky.
  2273. * @param int $post_id Post ID.
  2274. */
  2275. return apply_filters( 'is_sticky', $is_sticky, $post_id );
  2276. }
  2277. /**
  2278. * Sanitizes every post field.
  2279. *
  2280. * If the context is 'raw', then the post object or array will get minimal
  2281. * sanitization of the integer fields.
  2282. *
  2283. * @since 2.3.0
  2284. *
  2285. * @see sanitize_post_field()
  2286. *
  2287. * @param object|WP_Post|array $post The post object or array
  2288. * @param string $context Optional. How to sanitize post fields.
  2289. * Accepts 'raw', 'edit', 'db', 'display',
  2290. * 'attribute', or 'js'. Default 'display'.
  2291. * @return object|WP_Post|array The now sanitized post object or array (will be the
  2292. * same type as `$post`).
  2293. */
  2294. function sanitize_post( $post, $context = 'display' ) {
  2295. if ( is_object( $post ) ) {
  2296. // Check if post already filtered for this context.
  2297. if ( isset( $post->filter ) && $context == $post->filter ) {
  2298. return $post;
  2299. }
  2300. if ( ! isset( $post->ID ) ) {
  2301. $post->ID = 0;
  2302. }
  2303. foreach ( array_keys( get_object_vars( $post ) ) as $field ) {
  2304. $post->$field = sanitize_post_field( $field, $post->$field, $post->ID, $context );
  2305. }
  2306. $post->filter = $context;
  2307. } elseif ( is_array( $post ) ) {
  2308. // Check if post already filtered for this context.
  2309. if ( isset( $post['filter'] ) && $context == $post['filter'] ) {
  2310. return $post;
  2311. }
  2312. if ( ! isset( $post['ID'] ) ) {
  2313. $post['ID'] = 0;
  2314. }
  2315. foreach ( array_keys( $post ) as $field ) {
  2316. $post[ $field ] = sanitize_post_field( $field, $post[ $field ], $post['ID'], $context );
  2317. }
  2318. $post['filter'] = $context;
  2319. }
  2320. return $post;
  2321. }
  2322. /**
  2323. * Sanitizes a post field based on context.
  2324. *
  2325. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and
  2326. * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
  2327. * are treated like 'display' when calling filters.
  2328. *
  2329. * @since 2.3.0
  2330. * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
  2331. *
  2332. * @param string $field The Post Object field name.
  2333. * @param mixed $value The Post Object value.
  2334. * @param int $post_id Post ID.
  2335. * @param string $context Optional. How to sanitize the field. Possible values are 'raw', 'edit',
  2336. * 'db', 'display', 'attribute' and 'js'. Default 'display'.
  2337. * @return mixed Sanitized value.
  2338. */
  2339. function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
  2340. $int_fields = array( 'ID', 'post_parent', 'menu_order' );
  2341. if ( in_array( $field, $int_fields, true ) ) {
  2342. $value = (int) $value;
  2343. }
  2344. // Fields which contain arrays of integers.
  2345. $array_int_fields = array( 'ancestors' );
  2346. if ( in_array( $field, $array_int_fields, true ) ) {
  2347. $value = array_map( 'absint', $value );
  2348. return $value;
  2349. }
  2350. if ( 'raw' === $context ) {
  2351. return $value;
  2352. }
  2353. $prefixed = false;
  2354. if ( false !== strpos( $field, 'post_' ) ) {
  2355. $prefixed = true;
  2356. $field_no_prefix = str_replace( 'post_', '', $field );
  2357. }
  2358. if ( 'edit' === $context ) {
  2359. $format_to_edit = array( 'post_content', 'post_excerpt', 'post_title', 'post_password' );
  2360. if ( $prefixed ) {
  2361. /**
  2362. * Filters the value of a specific post field to edit.
  2363. *
  2364. * The dynamic portion of the hook name, `$field`, refers to the post
  2365. * field name.
  2366. *
  2367. * @since 2.3.0
  2368. *
  2369. * @param mixed $value Value of the post field.
  2370. * @param int $post_id Post ID.
  2371. */
  2372. $value = apply_filters( "edit_{$field}", $value, $post_id );
  2373. /**
  2374. * Filters the value of a specific post field to edit.
  2375. *
  2376. * The dynamic portion of the hook name, `$field_no_prefix`, refers to
  2377. * the post field name.
  2378. *
  2379. * @since 2.3.0
  2380. *
  2381. * @param mixed $value Value of the post field.
  2382. * @param int $post_id Post ID.
  2383. */
  2384. $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
  2385. } else {
  2386. $value = apply_filters( "edit_post_{$field}", $value, $post_id );
  2387. }
  2388. if ( in_array( $field, $format_to_edit, true ) ) {
  2389. if ( 'post_content' === $field ) {
  2390. $value = format_to_edit( $value, user_can_richedit() );
  2391. } else {
  2392. $value = format_to_edit( $value );
  2393. }
  2394. } else {
  2395. $value = esc_attr( $value );
  2396. }
  2397. } elseif ( 'db' === $context ) {
  2398. if ( $prefixed ) {
  2399. /**
  2400. * Filters the value of a specific post field before saving.
  2401. *
  2402. * The dynamic portion of the hook name, `$field`, refers to the post
  2403. * field name.
  2404. *
  2405. * @since 2.3.0
  2406. *
  2407. * @param mixed $value Value of the post field.
  2408. */
  2409. $value = apply_filters( "pre_{$field}", $value );
  2410. /**
  2411. * Filters the value of a specific field before saving.
  2412. *
  2413. * The dynamic portion of the hook name, `$field_no_prefix`, refers
  2414. * to the post field name.
  2415. *
  2416. * @since 2.3.0
  2417. *
  2418. * @param mixed $value Value of the post field.
  2419. */
  2420. $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
  2421. } else {
  2422. $value = apply_filters( "pre_post_{$field}", $value );
  2423. /**
  2424. * Filters the value of a specific post field before saving.
  2425. *
  2426. * The dynamic portion of the hook name, `$field`, refers to the post
  2427. * field name.
  2428. *
  2429. * @since 2.3.0
  2430. *
  2431. * @param mixed $value Value of the post field.
  2432. */
  2433. $value = apply_filters( "{$field}_pre", $value );
  2434. }
  2435. } else {
  2436. // Use display filters by default.
  2437. if ( $prefixed ) {
  2438. /**
  2439. * Filters the value of a specific post field for display.
  2440. *
  2441. * The dynamic portion of the hook name, `$field`, refers to the post
  2442. * field name.
  2443. *
  2444. * @since 2.3.0
  2445. *
  2446. * @param mixed $value Value of the prefixed post field.
  2447. * @param int $post_id Post ID.
  2448. * @param string $context Context for how to sanitize the field.
  2449. * Accepts 'raw', 'edit', 'db', 'display',
  2450. * 'attribute', or 'js'. Default 'display'.
  2451. */
  2452. $value = apply_filters( "{$field}", $value, $post_id, $context );
  2453. } else {
  2454. $value = apply_filters( "post_{$field}", $value, $post_id, $context );
  2455. }
  2456. if ( 'attribute' === $context ) {
  2457. $value = esc_attr( $value );
  2458. } elseif ( 'js' === $context ) {
  2459. $value = esc_js( $value );
  2460. }
  2461. }
  2462. // Restore the type for integer fields after esc_attr().
  2463. if ( in_array( $field, $int_fields, true ) ) {
  2464. $value = (int) $value;
  2465. }
  2466. return $value;
  2467. }
  2468. /**
  2469. * Make a post sticky.
  2470. *
  2471. * Sticky posts should be displayed at the top of the front page.
  2472. *
  2473. * @since 2.7.0
  2474. *
  2475. * @param int $post_id Post ID.
  2476. */
  2477. function stick_post( $post_id ) {
  2478. $post_id = (int) $post_id;
  2479. $stickies = get_option( 'sticky_posts' );
  2480. $updated = false;
  2481. if ( ! is_array( $stickies ) ) {
  2482. $stickies = array( $post_id );
  2483. } else {
  2484. $stickies = array_unique( array_map( 'intval', $stickies ) );
  2485. }
  2486. if ( ! in_array( $post_id, $stickies, true ) ) {
  2487. $stickies[] = $post_id;
  2488. $updated = update_option( 'sticky_posts', array_values( $stickies ) );
  2489. }
  2490. if ( $updated ) {
  2491. /**
  2492. * Fires once a post has been added to the sticky list.
  2493. *
  2494. * @since 4.6.0
  2495. *
  2496. * @param int $post_id ID of the post that was stuck.
  2497. */
  2498. do_action( 'post_stuck', $post_id );
  2499. }
  2500. }
  2501. /**
  2502. * Un-stick a post.
  2503. *
  2504. * Sticky posts should be displayed at the top of the front page.
  2505. *
  2506. * @since 2.7.0
  2507. *
  2508. * @param int $post_id Post ID.
  2509. */
  2510. function unstick_post( $post_id ) {
  2511. $post_id = (int) $post_id;
  2512. $stickies = get_option( 'sticky_posts' );
  2513. if ( ! is_array( $stickies ) ) {
  2514. return;
  2515. }
  2516. $stickies = array_values( array_unique( array_map( 'intval', $stickies ) ) );
  2517. if ( ! in_array( $post_id, $stickies, true ) ) {
  2518. return;
  2519. }
  2520. $offset = array_search( $post_id, $stickies, true );
  2521. if ( false === $offset ) {
  2522. return;
  2523. }
  2524. array_splice( $stickies, $offset, 1 );
  2525. $updated = update_option( 'sticky_posts', $stickies );
  2526. if ( $updated ) {
  2527. /**
  2528. * Fires once a post has been removed from the sticky list.
  2529. *
  2530. * @since 4.6.0
  2531. *
  2532. * @param int $post_id ID of the post that was unstuck.
  2533. */
  2534. do_action( 'post_unstuck', $post_id );
  2535. }
  2536. }
  2537. /**
  2538. * Return the cache key for wp_count_posts() based on the passed arguments.
  2539. *
  2540. * @since 3.9.0
  2541. * @access private
  2542. *
  2543. * @param string $type Optional. Post type to retrieve count Default 'post'.
  2544. * @param string $perm Optional. 'readable' or empty. Default empty.
  2545. * @return string The cache key.
  2546. */
  2547. function _count_posts_cache_key( $type = 'post', $perm = '' ) {
  2548. $cache_key = 'posts-' . $type;
  2549. if ( 'readable' === $perm && is_user_logged_in() ) {
  2550. $post_type_object = get_post_type_object( $type );
  2551. if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
  2552. $cache_key .= '_' . $perm . '_' . get_current_user_id();
  2553. }
  2554. }
  2555. return $cache_key;
  2556. }
  2557. /**
  2558. * Count number of posts of a post type and if user has permissions to view.
  2559. *
  2560. * This function provides an efficient method of finding the amount of post's
  2561. * type a blog has. Another method is to count the amount of items in
  2562. * get_posts(), but that method has a lot of overhead with doing so. Therefore,
  2563. * when developing for 2.5+, use this function instead.
  2564. *
  2565. * The $perm parameter checks for 'readable' value and if the user can read
  2566. * private posts, it will display that for the user that is signed in.
  2567. *
  2568. * @since 2.5.0
  2569. *
  2570. * @global wpdb $wpdb WordPress database abstraction object.
  2571. *
  2572. * @param string $type Optional. Post type to retrieve count. Default 'post'.
  2573. * @param string $perm Optional. 'readable' or empty. Default empty.
  2574. * @return object Number of posts for each status.
  2575. */
  2576. function wp_count_posts( $type = 'post', $perm = '' ) {
  2577. global $wpdb;
  2578. if ( ! post_type_exists( $type ) ) {
  2579. return new stdClass;
  2580. }
  2581. $cache_key = _count_posts_cache_key( $type, $perm );
  2582. $counts = wp_cache_get( $cache_key, 'counts' );
  2583. if ( false !== $counts ) {
  2584. // We may have cached this before every status was registered.
  2585. foreach ( get_post_stati() as $status ) {
  2586. if ( ! isset( $counts->{$status} ) ) {
  2587. $counts->{$status} = 0;
  2588. }
  2589. }
  2590. /** This filter is documented in wp-includes/post.php */
  2591. return apply_filters( 'wp_count_posts', $counts, $type, $perm );
  2592. }
  2593. $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
  2594. if ( 'readable' === $perm && is_user_logged_in() ) {
  2595. $post_type_object = get_post_type_object( $type );
  2596. if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
  2597. $query .= $wpdb->prepare(
  2598. " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
  2599. get_current_user_id()
  2600. );
  2601. }
  2602. }
  2603. $query .= ' GROUP BY post_status';
  2604. $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
  2605. $counts = array_fill_keys( get_post_stati(), 0 );
  2606. foreach ( $results as $row ) {
  2607. $counts[ $row['post_status'] ] = $row['num_posts'];
  2608. }
  2609. $counts = (object) $counts;
  2610. wp_cache_set( $cache_key, $counts, 'counts' );
  2611. /**
  2612. * Modify returned post counts by status for the current post type.
  2613. *
  2614. * @since 3.7.0
  2615. *
  2616. * @param object $counts An object containing the current post_type's post
  2617. * counts by status.
  2618. * @param string $type Post type.
  2619. * @param string $perm The permission to determine if the posts are 'readable'
  2620. * by the current user.
  2621. */
  2622. return apply_filters( 'wp_count_posts', $counts, $type, $perm );
  2623. }
  2624. /**
  2625. * Count number of attachments for the mime type(s).
  2626. *
  2627. * If you set the optional mime_type parameter, then an array will still be
  2628. * returned, but will only have the item you are looking for. It does not give
  2629. * you the number of attachments that are children of a post. You can get that
  2630. * by counting the number of children that post has.
  2631. *
  2632. * @since 2.5.0
  2633. *
  2634. * @global wpdb $wpdb WordPress database abstraction object.
  2635. *
  2636. * @param string|string[] $mime_type Optional. Array or comma-separated list of
  2637. * MIME patterns. Default empty.
  2638. * @return object An object containing the attachment counts by mime type.
  2639. */
  2640. function wp_count_attachments( $mime_type = '' ) {
  2641. global $wpdb;
  2642. $and = wp_post_mime_type_where( $mime_type );
  2643. $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
  2644. $counts = array();
  2645. foreach ( (array) $count as $row ) {
  2646. $counts[ $row['post_mime_type'] ] = $row['num_posts'];
  2647. }
  2648. $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and" );
  2649. /**
  2650. * Modify returned attachment counts by mime type.
  2651. *
  2652. * @since 3.7.0
  2653. *
  2654. * @param object $counts An object containing the attachment counts by
  2655. * mime type.
  2656. * @param string|string[] $mime_type Array or comma-separated list of MIME patterns.
  2657. */
  2658. return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
  2659. }
  2660. /**
  2661. * Get default post mime types.
  2662. *
  2663. * @since 2.9.0
  2664. * @since 5.3.0 Added the 'Documents', 'Spreadsheets', and 'Archives' mime type groups.
  2665. *
  2666. * @return array List of post mime types.
  2667. */
  2668. function get_post_mime_types() {
  2669. $post_mime_types = array( // array( adj, noun )
  2670. 'image' => array(
  2671. __( 'Images' ),
  2672. __( 'Manage Images' ),
  2673. /* translators: %s: Number of images. */
  2674. _n_noop(
  2675. 'Image <span class="count">(%s)</span>',
  2676. 'Images <span class="count">(%s)</span>'
  2677. ),
  2678. ),
  2679. 'audio' => array(
  2680. __( 'Audio' ),
  2681. __( 'Manage Audio' ),
  2682. /* translators: %s: Number of audio files. */
  2683. _n_noop(
  2684. 'Audio <span class="count">(%s)</span>',
  2685. 'Audio <span class="count">(%s)</span>'
  2686. ),
  2687. ),
  2688. 'video' => array(
  2689. __( 'Video' ),
  2690. __( 'Manage Video' ),
  2691. /* translators: %s: Number of video files. */
  2692. _n_noop(
  2693. 'Video <span class="count">(%s)</span>',
  2694. 'Video <span class="count">(%s)</span>'
  2695. ),
  2696. ),
  2697. 'document' => array(
  2698. __( 'Documents' ),
  2699. __( 'Manage Documents' ),
  2700. /* translators: %s: Number of documents. */
  2701. _n_noop(
  2702. 'Document <span class="count">(%s)</span>',
  2703. 'Documents <span class="count">(%s)</span>'
  2704. ),
  2705. ),
  2706. 'spreadsheet' => array(
  2707. __( 'Spreadsheets' ),
  2708. __( 'Manage Spreadsheets' ),
  2709. /* translators: %s: Number of spreadsheets. */
  2710. _n_noop(
  2711. 'Spreadsheet <span class="count">(%s)</span>',
  2712. 'Spreadsheets <span class="count">(%s)</span>'
  2713. ),
  2714. ),
  2715. 'archive' => array(
  2716. _x( 'Archives', 'file type group' ),
  2717. __( 'Manage Archives' ),
  2718. /* translators: %s: Number of archives. */
  2719. _n_noop(
  2720. 'Archive <span class="count">(%s)</span>',
  2721. 'Archives <span class="count">(%s)</span>'
  2722. ),
  2723. ),
  2724. );
  2725. $ext_types = wp_get_ext_types();
  2726. $mime_types = wp_get_mime_types();
  2727. foreach ( $post_mime_types as $group => $labels ) {
  2728. if ( in_array( $group, array( 'image', 'audio', 'video' ), true ) ) {
  2729. continue;
  2730. }
  2731. if ( ! isset( $ext_types[ $group ] ) ) {
  2732. unset( $post_mime_types[ $group ] );
  2733. continue;
  2734. }
  2735. $group_mime_types = array();
  2736. foreach ( $ext_types[ $group ] as $extension ) {
  2737. foreach ( $mime_types as $exts => $mime ) {
  2738. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  2739. $group_mime_types[] = $mime;
  2740. break;
  2741. }
  2742. }
  2743. }
  2744. $group_mime_types = implode( ',', array_unique( $group_mime_types ) );
  2745. $post_mime_types[ $group_mime_types ] = $labels;
  2746. unset( $post_mime_types[ $group ] );
  2747. }
  2748. /**
  2749. * Filters the default list of post mime types.
  2750. *
  2751. * @since 2.5.0
  2752. *
  2753. * @param array $post_mime_types Default list of post mime types.
  2754. */
  2755. return apply_filters( 'post_mime_types', $post_mime_types );
  2756. }
  2757. /**
  2758. * Check a MIME-Type against a list.
  2759. *
  2760. * If the wildcard_mime_types parameter is a string, it must be comma separated
  2761. * list. If the real_mime_types is a string, it is also comma separated to
  2762. * create the list.
  2763. *
  2764. * @since 2.5.0
  2765. *
  2766. * @param string|string[] $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
  2767. * or flash (same as *flash*).
  2768. * @param string|string[] $real_mime_types Real post mime type values.
  2769. * @return array array(wildcard=>array(real types)).
  2770. */
  2771. function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
  2772. $matches = array();
  2773. if ( is_string( $wildcard_mime_types ) ) {
  2774. $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
  2775. }
  2776. if ( is_string( $real_mime_types ) ) {
  2777. $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
  2778. }
  2779. $patternses = array();
  2780. $wild = '[-._a-z0-9]*';
  2781. foreach ( (array) $wildcard_mime_types as $type ) {
  2782. $mimes = array_map( 'trim', explode( ',', $type ) );
  2783. foreach ( $mimes as $mime ) {
  2784. $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
  2785. $patternses[][ $type ] = "^$regex$";
  2786. if ( false === strpos( $mime, '/' ) ) {
  2787. $patternses[][ $type ] = "^$regex/";
  2788. $patternses[][ $type ] = $regex;
  2789. }
  2790. }
  2791. }
  2792. asort( $patternses );
  2793. foreach ( $patternses as $patterns ) {
  2794. foreach ( $patterns as $type => $pattern ) {
  2795. foreach ( (array) $real_mime_types as $real ) {
  2796. if ( preg_match( "#$pattern#", $real )
  2797. && ( empty( $matches[ $type ] ) || false === array_search( $real, $matches[ $type ], true ) )
  2798. ) {
  2799. $matches[ $type ][] = $real;
  2800. }
  2801. }
  2802. }
  2803. }
  2804. return $matches;
  2805. }
  2806. /**
  2807. * Convert MIME types into SQL.
  2808. *
  2809. * @since 2.5.0
  2810. *
  2811. * @param string|string[] $post_mime_types List of mime types or comma separated string
  2812. * of mime types.
  2813. * @param string $table_alias Optional. Specify a table alias, if needed.
  2814. * Default empty.
  2815. * @return string The SQL AND clause for mime searching.
  2816. */
  2817. function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
  2818. $where = '';
  2819. $wildcards = array( '', '%', '%/%' );
  2820. if ( is_string( $post_mime_types ) ) {
  2821. $post_mime_types = array_map( 'trim', explode( ',', $post_mime_types ) );
  2822. }
  2823. $wheres = array();
  2824. foreach ( (array) $post_mime_types as $mime_type ) {
  2825. $mime_type = preg_replace( '/\s/', '', $mime_type );
  2826. $slashpos = strpos( $mime_type, '/' );
  2827. if ( false !== $slashpos ) {
  2828. $mime_group = preg_replace( '/[^-*.a-zA-Z0-9]/', '', substr( $mime_type, 0, $slashpos ) );
  2829. $mime_subgroup = preg_replace( '/[^-*.+a-zA-Z0-9]/', '', substr( $mime_type, $slashpos + 1 ) );
  2830. if ( empty( $mime_subgroup ) ) {
  2831. $mime_subgroup = '*';
  2832. } else {
  2833. $mime_subgroup = str_replace( '/', '', $mime_subgroup );
  2834. }
  2835. $mime_pattern = "$mime_group/$mime_subgroup";
  2836. } else {
  2837. $mime_pattern = preg_replace( '/[^-*.a-zA-Z0-9]/', '', $mime_type );
  2838. if ( false === strpos( $mime_pattern, '*' ) ) {
  2839. $mime_pattern .= '/*';
  2840. }
  2841. }
  2842. $mime_pattern = preg_replace( '/\*+/', '%', $mime_pattern );
  2843. if ( in_array( $mime_type, $wildcards, true ) ) {
  2844. return '';
  2845. }
  2846. if ( false !== strpos( $mime_pattern, '%' ) ) {
  2847. $wheres[] = empty( $table_alias ) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
  2848. } else {
  2849. $wheres[] = empty( $table_alias ) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
  2850. }
  2851. }
  2852. if ( ! empty( $wheres ) ) {
  2853. $where = ' AND (' . implode( ' OR ', $wheres ) . ') ';
  2854. }
  2855. return $where;
  2856. }
  2857. /**
  2858. * Trash or delete a post or page.
  2859. *
  2860. * When the post and page is permanently deleted, everything that is tied to
  2861. * it is deleted also. This includes comments, post meta fields, and terms
  2862. * associated with the post.
  2863. *
  2864. * The post or page is moved to Trash instead of permanently deleted unless
  2865. * Trash is disabled, item is already in the Trash, or $force_delete is true.
  2866. *
  2867. * @since 1.0.0
  2868. *
  2869. * @global wpdb $wpdb WordPress database abstraction object.
  2870. * @see wp_delete_attachment()
  2871. * @see wp_trash_post()
  2872. *
  2873. * @param int $postid Optional. Post ID. Default 0.
  2874. * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
  2875. * Default false.
  2876. * @return WP_Post|false|null Post data on success, false or null on failure.
  2877. */
  2878. function wp_delete_post( $postid = 0, $force_delete = false ) {
  2879. global $wpdb;
  2880. $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid ) );
  2881. if ( ! $post ) {
  2882. return $post;
  2883. }
  2884. $post = get_post( $post );
  2885. if ( ! $force_delete && ( 'post' === $post->post_type || 'page' === $post->post_type ) && 'trash' !== get_post_status( $postid ) && EMPTY_TRASH_DAYS ) {
  2886. return wp_trash_post( $postid );
  2887. }
  2888. if ( 'attachment' === $post->post_type ) {
  2889. return wp_delete_attachment( $postid, $force_delete );
  2890. }
  2891. /**
  2892. * Filters whether a post deletion should take place.
  2893. *
  2894. * @since 4.4.0
  2895. *
  2896. * @param bool|null $delete Whether to go forward with deletion.
  2897. * @param WP_Post $post Post object.
  2898. * @param bool $force_delete Whether to bypass the Trash.
  2899. */
  2900. $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
  2901. if ( null !== $check ) {
  2902. return $check;
  2903. }
  2904. /**
  2905. * Fires before a post is deleted, at the start of wp_delete_post().
  2906. *
  2907. * @since 3.2.0
  2908. * @since 5.5.0 Added the `$post` parameter.
  2909. *
  2910. * @see wp_delete_post()
  2911. *
  2912. * @param int $postid Post ID.
  2913. * @param WP_Post $post Post object.
  2914. */
  2915. do_action( 'before_delete_post', $postid, $post );
  2916. delete_post_meta( $postid, '_wp_trash_meta_status' );
  2917. delete_post_meta( $postid, '_wp_trash_meta_time' );
  2918. wp_delete_object_term_relationships( $postid, get_object_taxonomies( $post->post_type ) );
  2919. $parent_data = array( 'post_parent' => $post->post_parent );
  2920. $parent_where = array( 'post_parent' => $postid );
  2921. if ( is_post_type_hierarchical( $post->post_type ) ) {
  2922. // Point children of this page to its parent, also clean the cache of affected children.
  2923. $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
  2924. $children = $wpdb->get_results( $children_query );
  2925. if ( $children ) {
  2926. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
  2927. }
  2928. }
  2929. // Do raw query. wp_get_post_revisions() is filtered.
  2930. $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
  2931. // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
  2932. foreach ( $revision_ids as $revision_id ) {
  2933. wp_delete_post_revision( $revision_id );
  2934. }
  2935. // Point all attachments to this post up one level.
  2936. $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
  2937. wp_defer_comment_counting( true );
  2938. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ) );
  2939. foreach ( $comment_ids as $comment_id ) {
  2940. wp_delete_comment( $comment_id, true );
  2941. }
  2942. wp_defer_comment_counting( false );
  2943. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ) );
  2944. foreach ( $post_meta_ids as $mid ) {
  2945. delete_metadata_by_mid( 'post', $mid );
  2946. }
  2947. /**
  2948. * Fires immediately before a post is deleted from the database.
  2949. *
  2950. * @since 1.2.0
  2951. * @since 5.5.0 Added the `$post` parameter.
  2952. *
  2953. * @param int $postid Post ID.
  2954. * @param WP_Post $post Post object.
  2955. */
  2956. do_action( 'delete_post', $postid, $post );
  2957. $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
  2958. if ( ! $result ) {
  2959. return false;
  2960. }
  2961. /**
  2962. * Fires immediately after a post is deleted from the database.
  2963. *
  2964. * @since 2.2.0
  2965. * @since 5.5.0 Added the `$post` parameter.
  2966. *
  2967. * @param int $postid Post ID.
  2968. * @param WP_Post $post Post object.
  2969. */
  2970. do_action( 'deleted_post', $postid, $post );
  2971. clean_post_cache( $post );
  2972. if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
  2973. foreach ( $children as $child ) {
  2974. clean_post_cache( $child );
  2975. }
  2976. }
  2977. wp_clear_scheduled_hook( 'publish_future_post', array( $postid ) );
  2978. /**
  2979. * Fires after a post is deleted, at the conclusion of wp_delete_post().
  2980. *
  2981. * @since 3.2.0
  2982. * @since 5.5.0 Added the `$post` parameter.
  2983. *
  2984. * @see wp_delete_post()
  2985. *
  2986. * @param int $postid Post ID.
  2987. * @param WP_Post $post Post object.
  2988. */
  2989. do_action( 'after_delete_post', $postid, $post );
  2990. return $post;
  2991. }
  2992. /**
  2993. * Reset the page_on_front, show_on_front, and page_for_post settings when
  2994. * a linked page is deleted or trashed.
  2995. *
  2996. * Also ensures the post is no longer sticky.
  2997. *
  2998. * @since 3.7.0
  2999. * @access private
  3000. *
  3001. * @param int $post_id Post ID.
  3002. */
  3003. function _reset_front_page_settings_for_post( $post_id ) {
  3004. $post = get_post( $post_id );
  3005. if ( 'page' === $post->post_type ) {
  3006. /*
  3007. * If the page is defined in option page_on_front or post_for_posts,
  3008. * adjust the corresponding options.
  3009. */
  3010. if ( get_option( 'page_on_front' ) == $post->ID ) {
  3011. update_option( 'show_on_front', 'posts' );
  3012. update_option( 'page_on_front', 0 );
  3013. }
  3014. if ( get_option( 'page_for_posts' ) == $post->ID ) {
  3015. update_option( 'page_for_posts', 0 );
  3016. }
  3017. }
  3018. unstick_post( $post->ID );
  3019. }
  3020. /**
  3021. * Move a post or page to the Trash
  3022. *
  3023. * If Trash is disabled, the post or page is permanently deleted.
  3024. *
  3025. * @since 2.9.0
  3026. *
  3027. * @see wp_delete_post()
  3028. *
  3029. * @param int $post_id Optional. Post ID. Default is ID of the global $post
  3030. * if EMPTY_TRASH_DAYS equals true.
  3031. * @return WP_Post|false|null Post data on success, false or null on failure.
  3032. */
  3033. function wp_trash_post( $post_id = 0 ) {
  3034. if ( ! EMPTY_TRASH_DAYS ) {
  3035. return wp_delete_post( $post_id, true );
  3036. }
  3037. $post = get_post( $post_id );
  3038. if ( ! $post ) {
  3039. return $post;
  3040. }
  3041. if ( 'trash' === $post->post_status ) {
  3042. return false;
  3043. }
  3044. /**
  3045. * Filters whether a post trashing should take place.
  3046. *
  3047. * @since 4.9.0
  3048. *
  3049. * @param bool|null $trash Whether to go forward with trashing.
  3050. * @param WP_Post $post Post object.
  3051. */
  3052. $check = apply_filters( 'pre_trash_post', null, $post );
  3053. if ( null !== $check ) {
  3054. return $check;
  3055. }
  3056. /**
  3057. * Fires before a post is sent to the Trash.
  3058. *
  3059. * @since 3.3.0
  3060. *
  3061. * @param int $post_id Post ID.
  3062. */
  3063. do_action( 'wp_trash_post', $post_id );
  3064. add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status );
  3065. add_post_meta( $post_id, '_wp_trash_meta_time', time() );
  3066. $post_updated = wp_update_post(
  3067. array(
  3068. 'ID' => $post_id,
  3069. 'post_status' => 'trash',
  3070. )
  3071. );
  3072. if ( ! $post_updated ) {
  3073. return false;
  3074. }
  3075. wp_trash_post_comments( $post_id );
  3076. /**
  3077. * Fires after a post is sent to the Trash.
  3078. *
  3079. * @since 2.9.0
  3080. *
  3081. * @param int $post_id Post ID.
  3082. */
  3083. do_action( 'trashed_post', $post_id );
  3084. return $post;
  3085. }
  3086. /**
  3087. * Restores a post from the Trash.
  3088. *
  3089. * @since 2.9.0
  3090. * @since 5.6.0 An untrashed post is now returned to 'draft' status by default, except for
  3091. * attachments which are returned to their original 'inherit' status.
  3092. *
  3093. * @param int $post_id Optional. Post ID. Default is ID of the global `$post`.
  3094. * @return WP_Post|false|null Post data on success, false or null on failure.
  3095. */
  3096. function wp_untrash_post( $post_id = 0 ) {
  3097. $post = get_post( $post_id );
  3098. if ( ! $post ) {
  3099. return $post;
  3100. }
  3101. $post_id = $post->ID;
  3102. if ( 'trash' !== $post->post_status ) {
  3103. return false;
  3104. }
  3105. $previous_status = get_post_meta( $post_id, '_wp_trash_meta_status', true );
  3106. /**
  3107. * Filters whether a post untrashing should take place.
  3108. *
  3109. * @since 4.9.0
  3110. * @since 5.6.0 The `$previous_status` parameter was added.
  3111. *
  3112. * @param bool|null $untrash Whether to go forward with untrashing.
  3113. * @param WP_Post $post Post object.
  3114. * @param string $previous_status The status of the post at the point where it was trashed.
  3115. */
  3116. $check = apply_filters( 'pre_untrash_post', null, $post, $previous_status );
  3117. if ( null !== $check ) {
  3118. return $check;
  3119. }
  3120. /**
  3121. * Fires before a post is restored from the Trash.
  3122. *
  3123. * @since 2.9.0
  3124. * @since 5.6.0 The `$previous_status` parameter was added.
  3125. *
  3126. * @param int $post_id Post ID.
  3127. * @param string $previous_status The status of the post at the point where it was trashed.
  3128. */
  3129. do_action( 'untrash_post', $post_id, $previous_status );
  3130. $new_status = ( 'attachment' === $post->post_type ) ? 'inherit' : 'draft';
  3131. /**
  3132. * Filters the status that a post gets assigned when it is restored from the trash (untrashed).
  3133. *
  3134. * By default posts that are restored will be assigned a status of 'draft'. Return the value of `$previous_status`
  3135. * in order to assign the status that the post had before it was trashed. The `wp_untrash_post_set_previous_status()`
  3136. * function is available for this.
  3137. *
  3138. * Prior to WordPress 5.6.0, restored posts were always assigned their original status.
  3139. *
  3140. * @since 5.6.0
  3141. *
  3142. * @param string $new_status The new status of the post being restored.
  3143. * @param int $post_id The ID of the post being restored.
  3144. * @param string $previous_status The status of the post at the point where it was trashed.
  3145. */
  3146. $post_status = apply_filters( 'wp_untrash_post_status', $new_status, $post_id, $previous_status );
  3147. delete_post_meta( $post_id, '_wp_trash_meta_status' );
  3148. delete_post_meta( $post_id, '_wp_trash_meta_time' );
  3149. $post_updated = wp_update_post(
  3150. array(
  3151. 'ID' => $post_id,
  3152. 'post_status' => $post_status,
  3153. )
  3154. );
  3155. if ( ! $post_updated ) {
  3156. return false;
  3157. }
  3158. wp_untrash_post_comments( $post_id );
  3159. /**
  3160. * Fires after a post is restored from the Trash.
  3161. *
  3162. * @since 2.9.0
  3163. * @since 5.6.0 The `$previous_status` parameter was added.
  3164. *
  3165. * @param int $post_id Post ID.
  3166. * @param string $previous_status The status of the post at the point where it was trashed.
  3167. */
  3168. do_action( 'untrashed_post', $post_id, $previous_status );
  3169. return $post;
  3170. }
  3171. /**
  3172. * Moves comments for a post to the Trash.
  3173. *
  3174. * @since 2.9.0
  3175. *
  3176. * @global wpdb $wpdb WordPress database abstraction object.
  3177. *
  3178. * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
  3179. * @return mixed|void False on failure.
  3180. */
  3181. function wp_trash_post_comments( $post = null ) {
  3182. global $wpdb;
  3183. $post = get_post( $post );
  3184. if ( ! $post ) {
  3185. return;
  3186. }
  3187. $post_id = $post->ID;
  3188. /**
  3189. * Fires before comments are sent to the Trash.
  3190. *
  3191. * @since 2.9.0
  3192. *
  3193. * @param int $post_id Post ID.
  3194. */
  3195. do_action( 'trash_post_comments', $post_id );
  3196. $comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ) );
  3197. if ( ! $comments ) {
  3198. return;
  3199. }
  3200. // Cache current status for each comment.
  3201. $statuses = array();
  3202. foreach ( $comments as $comment ) {
  3203. $statuses[ $comment->comment_ID ] = $comment->comment_approved;
  3204. }
  3205. add_post_meta( $post_id, '_wp_trash_meta_comments_status', $statuses );
  3206. // Set status for all comments to post-trashed.
  3207. $result = $wpdb->update( $wpdb->comments, array( 'comment_approved' => 'post-trashed' ), array( 'comment_post_ID' => $post_id ) );
  3208. clean_comment_cache( array_keys( $statuses ) );
  3209. /**
  3210. * Fires after comments are sent to the Trash.
  3211. *
  3212. * @since 2.9.0
  3213. *
  3214. * @param int $post_id Post ID.
  3215. * @param array $statuses Array of comment statuses.
  3216. */
  3217. do_action( 'trashed_post_comments', $post_id, $statuses );
  3218. return $result;
  3219. }
  3220. /**
  3221. * Restore comments for a post from the Trash.
  3222. *
  3223. * @since 2.9.0
  3224. *
  3225. * @global wpdb $wpdb WordPress database abstraction object.
  3226. *
  3227. * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
  3228. * @return true|void
  3229. */
  3230. function wp_untrash_post_comments( $post = null ) {
  3231. global $wpdb;
  3232. $post = get_post( $post );
  3233. if ( ! $post ) {
  3234. return;
  3235. }
  3236. $post_id = $post->ID;
  3237. $statuses = get_post_meta( $post_id, '_wp_trash_meta_comments_status', true );
  3238. if ( ! $statuses ) {
  3239. return true;
  3240. }
  3241. /**
  3242. * Fires before comments are restored for a post from the Trash.
  3243. *
  3244. * @since 2.9.0
  3245. *
  3246. * @param int $post_id Post ID.
  3247. */
  3248. do_action( 'untrash_post_comments', $post_id );
  3249. // Restore each comment to its original status.
  3250. $group_by_status = array();
  3251. foreach ( $statuses as $comment_id => $comment_status ) {
  3252. $group_by_status[ $comment_status ][] = $comment_id;
  3253. }
  3254. foreach ( $group_by_status as $status => $comments ) {
  3255. // Sanity check. This shouldn't happen.
  3256. if ( 'post-trashed' === $status ) {
  3257. $status = '0';
  3258. }
  3259. $comments_in = implode( ', ', array_map( 'intval', $comments ) );
  3260. $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
  3261. }
  3262. clean_comment_cache( array_keys( $statuses ) );
  3263. delete_post_meta( $post_id, '_wp_trash_meta_comments_status' );
  3264. /**
  3265. * Fires after comments are restored for a post from the Trash.
  3266. *
  3267. * @since 2.9.0
  3268. *
  3269. * @param int $post_id Post ID.
  3270. */
  3271. do_action( 'untrashed_post_comments', $post_id );
  3272. }
  3273. /**
  3274. * Retrieve the list of categories for a post.
  3275. *
  3276. * Compatibility layer for themes and plugins. Also an easy layer of abstraction
  3277. * away from the complexity of the taxonomy layer.
  3278. *
  3279. * @since 2.1.0
  3280. *
  3281. * @see wp_get_object_terms()
  3282. *
  3283. * @param int $post_id Optional. The Post ID. Does not default to the ID of the
  3284. * global $post. Default 0.
  3285. * @param array $args Optional. Category query parameters. Default empty array.
  3286. * See WP_Term_Query::__construct() for supported arguments.
  3287. * @return array|WP_Error List of categories. If the `$fields` argument passed via `$args` is 'all' or
  3288. * 'all_with_object_id', an array of WP_Term objects will be returned. If `$fields`
  3289. * is 'ids', an array of category IDs. If `$fields` is 'names', an array of category names.
  3290. * WP_Error object if 'category' taxonomy doesn't exist.
  3291. */
  3292. function wp_get_post_categories( $post_id = 0, $args = array() ) {
  3293. $post_id = (int) $post_id;
  3294. $defaults = array( 'fields' => 'ids' );
  3295. $args = wp_parse_args( $args, $defaults );
  3296. $cats = wp_get_object_terms( $post_id, 'category', $args );
  3297. return $cats;
  3298. }
  3299. /**
  3300. * Retrieve the tags for a post.
  3301. *
  3302. * There is only one default for this function, called 'fields' and by default
  3303. * is set to 'all'. There are other defaults that can be overridden in
  3304. * wp_get_object_terms().
  3305. *
  3306. * @since 2.3.0
  3307. *
  3308. * @param int $post_id Optional. The Post ID. Does not default to the ID of the
  3309. * global $post. Default 0.
  3310. * @param array $args Optional. Tag query parameters. Default empty array.
  3311. * See WP_Term_Query::__construct() for supported arguments.
  3312. * @return array|WP_Error Array of WP_Term objects on success or empty array if no tags were found.
  3313. * WP_Error object if 'post_tag' taxonomy doesn't exist.
  3314. */
  3315. function wp_get_post_tags( $post_id = 0, $args = array() ) {
  3316. return wp_get_post_terms( $post_id, 'post_tag', $args );
  3317. }
  3318. /**
  3319. * Retrieves the terms for a post.
  3320. *
  3321. * @since 2.8.0
  3322. *
  3323. * @param int $post_id Optional. The Post ID. Does not default to the ID of the
  3324. * global $post. Default 0.
  3325. * @param string|string[] $taxonomy Optional. The taxonomy slug or array of slugs for which
  3326. * to retrieve terms. Default 'post_tag'.
  3327. * @param array $args {
  3328. * Optional. Term query parameters. See WP_Term_Query::__construct() for supported arguments.
  3329. *
  3330. * @type string $fields Term fields to retrieve. Default 'all'.
  3331. * }
  3332. * @return array|WP_Error Array of WP_Term objects on success or empty array if no terms were found.
  3333. * WP_Error object if `$taxonomy` doesn't exist.
  3334. */
  3335. function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
  3336. $post_id = (int) $post_id;
  3337. $defaults = array( 'fields' => 'all' );
  3338. $args = wp_parse_args( $args, $defaults );
  3339. $tags = wp_get_object_terms( $post_id, $taxonomy, $args );
  3340. return $tags;
  3341. }
  3342. /**
  3343. * Retrieve a number of recent posts.
  3344. *
  3345. * @since 1.0.0
  3346. *
  3347. * @see get_posts()
  3348. *
  3349. * @param array $args Optional. Arguments to retrieve posts. Default empty array.
  3350. * @param string $output Optional. The required return type. One of OBJECT or ARRAY_A, which
  3351. * correspond to a WP_Post object or an associative array, respectively.
  3352. * Default ARRAY_A.
  3353. * @return array|false Array of recent posts, where the type of each element is determined
  3354. * by the `$output` parameter. Empty array on failure.
  3355. */
  3356. function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
  3357. if ( is_numeric( $args ) ) {
  3358. _deprecated_argument( __FUNCTION__, '3.1.0', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  3359. $args = array( 'numberposts' => absint( $args ) );
  3360. }
  3361. // Set default arguments.
  3362. $defaults = array(
  3363. 'numberposts' => 10,
  3364. 'offset' => 0,
  3365. 'category' => 0,
  3366. 'orderby' => 'post_date',
  3367. 'order' => 'DESC',
  3368. 'include' => '',
  3369. 'exclude' => '',
  3370. 'meta_key' => '',
  3371. 'meta_value' => '',
  3372. 'post_type' => 'post',
  3373. 'post_status' => 'draft, publish, future, pending, private',
  3374. 'suppress_filters' => true,
  3375. );
  3376. $parsed_args = wp_parse_args( $args, $defaults );
  3377. $results = get_posts( $parsed_args );
  3378. // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
  3379. if ( ARRAY_A === $output ) {
  3380. foreach ( $results as $key => $result ) {
  3381. $results[ $key ] = get_object_vars( $result );
  3382. }
  3383. return $results ? $results : array();
  3384. }
  3385. return $results ? $results : false;
  3386. }
  3387. /**
  3388. * Insert or update a post.
  3389. *
  3390. * If the $postarr parameter has 'ID' set to a value, then post will be updated.
  3391. *
  3392. * You can set the post date manually, by setting the values for 'post_date'
  3393. * and 'post_date_gmt' keys. You can close the comments or open the comments by
  3394. * setting the value for 'comment_status' key.
  3395. *
  3396. * @since 1.0.0
  3397. * @since 2.6.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
  3398. * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
  3399. * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
  3400. * @since 5.6.0 Added the `$fire_after_hooks` parameter.
  3401. *
  3402. * @see sanitize_post()
  3403. * @global wpdb $wpdb WordPress database abstraction object.
  3404. *
  3405. * @param array $postarr {
  3406. * An array of elements that make up a post to update or insert.
  3407. *
  3408. * @type int $ID The post ID. If equal to something other than 0,
  3409. * the post with that ID will be updated. Default 0.
  3410. * @type int $post_author The ID of the user who added the post. Default is
  3411. * the current user ID.
  3412. * @type string $post_date The date of the post. Default is the current time.
  3413. * @type string $post_date_gmt The date of the post in the GMT timezone. Default is
  3414. * the value of `$post_date`.
  3415. * @type mixed $post_content The post content. Default empty.
  3416. * @type string $post_content_filtered The filtered post content. Default empty.
  3417. * @type string $post_title The post title. Default empty.
  3418. * @type string $post_excerpt The post excerpt. Default empty.
  3419. * @type string $post_status The post status. Default 'draft'.
  3420. * @type string $post_type The post type. Default 'post'.
  3421. * @type string $comment_status Whether the post can accept comments. Accepts 'open' or 'closed'.
  3422. * Default is the value of 'default_comment_status' option.
  3423. * @type string $ping_status Whether the post can accept pings. Accepts 'open' or 'closed'.
  3424. * Default is the value of 'default_ping_status' option.
  3425. * @type string $post_password The password to access the post. Default empty.
  3426. * @type string $post_name The post name. Default is the sanitized post title
  3427. * when creating a new post.
  3428. * @type string $to_ping Space or carriage return-separated list of URLs to ping.
  3429. * Default empty.
  3430. * @type string $pinged Space or carriage return-separated list of URLs that have
  3431. * been pinged. Default empty.
  3432. * @type string $post_modified The date when the post was last modified. Default is
  3433. * the current time.
  3434. * @type string $post_modified_gmt The date when the post was last modified in the GMT
  3435. * timezone. Default is the current time.
  3436. * @type int $post_parent Set this for the post it belongs to, if any. Default 0.
  3437. * @type int $menu_order The order the post should be displayed in. Default 0.
  3438. * @type string $post_mime_type The mime type of the post. Default empty.
  3439. * @type string $guid Global Unique ID for referencing the post. Default empty.
  3440. * @type int $import_id The post ID to be used when inserting a new post.
  3441. * If specified, must not match any existing post ID. Default 0.
  3442. * @type int[] $post_category Array of category IDs.
  3443. * Defaults to value of the 'default_category' option.
  3444. * @type array $tags_input Array of tag names, slugs, or IDs. Default empty.
  3445. * @type array $tax_input Array of taxonomy terms keyed by their taxonomy name. Default empty.
  3446. * @type array $meta_input Array of post meta values keyed by their post meta key. Default empty.
  3447. * }
  3448. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  3449. * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
  3450. * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
  3451. */
  3452. function wp_insert_post( $postarr, $wp_error = false, $fire_after_hooks = true ) {
  3453. global $wpdb;
  3454. // Capture original pre-sanitized array for passing into filters.
  3455. $unsanitized_postarr = $postarr;
  3456. $user_id = get_current_user_id();
  3457. $defaults = array(
  3458. 'post_author' => $user_id,
  3459. 'post_content' => '',
  3460. 'post_content_filtered' => '',
  3461. 'post_title' => '',
  3462. 'post_excerpt' => '',
  3463. 'post_status' => 'draft',
  3464. 'post_type' => 'post',
  3465. 'comment_status' => '',
  3466. 'ping_status' => '',
  3467. 'post_password' => '',
  3468. 'to_ping' => '',
  3469. 'pinged' => '',
  3470. 'post_parent' => 0,
  3471. 'menu_order' => 0,
  3472. 'guid' => '',
  3473. 'import_id' => 0,
  3474. 'context' => '',
  3475. 'post_date' => '',
  3476. 'post_date_gmt' => '',
  3477. );
  3478. $postarr = wp_parse_args( $postarr, $defaults );
  3479. unset( $postarr['filter'] );
  3480. $postarr = sanitize_post( $postarr, 'db' );
  3481. // Are we updating or creating?
  3482. $post_ID = 0;
  3483. $update = false;
  3484. $guid = $postarr['guid'];
  3485. if ( ! empty( $postarr['ID'] ) ) {
  3486. $update = true;
  3487. // Get the post ID and GUID.
  3488. $post_ID = $postarr['ID'];
  3489. $post_before = get_post( $post_ID );
  3490. if ( is_null( $post_before ) ) {
  3491. if ( $wp_error ) {
  3492. return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
  3493. }
  3494. return 0;
  3495. }
  3496. $guid = get_post_field( 'guid', $post_ID );
  3497. $previous_status = get_post_field( 'post_status', $post_ID );
  3498. } else {
  3499. $previous_status = 'new';
  3500. $post_before = null;
  3501. }
  3502. $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
  3503. $post_title = $postarr['post_title'];
  3504. $post_content = $postarr['post_content'];
  3505. $post_excerpt = $postarr['post_excerpt'];
  3506. if ( isset( $postarr['post_name'] ) ) {
  3507. $post_name = $postarr['post_name'];
  3508. } elseif ( $update ) {
  3509. // For an update, don't modify the post_name if it wasn't supplied as an argument.
  3510. $post_name = $post_before->post_name;
  3511. }
  3512. $maybe_empty = 'attachment' !== $post_type
  3513. && ! $post_content && ! $post_title && ! $post_excerpt
  3514. && post_type_supports( $post_type, 'editor' )
  3515. && post_type_supports( $post_type, 'title' )
  3516. && post_type_supports( $post_type, 'excerpt' );
  3517. /**
  3518. * Filters whether the post should be considered "empty".
  3519. *
  3520. * The post is considered "empty" if both:
  3521. * 1. The post type supports the title, editor, and excerpt fields
  3522. * 2. The title, editor, and excerpt fields are all empty
  3523. *
  3524. * Returning a truthy value from the filter will effectively short-circuit
  3525. * the new post being inserted and return 0. If $wp_error is true, a WP_Error
  3526. * will be returned instead.
  3527. *
  3528. * @since 3.3.0
  3529. *
  3530. * @param bool $maybe_empty Whether the post should be considered "empty".
  3531. * @param array $postarr Array of post data.
  3532. */
  3533. if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
  3534. if ( $wp_error ) {
  3535. return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
  3536. } else {
  3537. return 0;
  3538. }
  3539. }
  3540. $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
  3541. if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash', 'auto-draft' ), true ) ) {
  3542. $post_status = 'inherit';
  3543. }
  3544. if ( ! empty( $postarr['post_category'] ) ) {
  3545. // Filter out empty terms.
  3546. $post_category = array_filter( $postarr['post_category'] );
  3547. }
  3548. // Make sure we set a valid category.
  3549. if ( empty( $post_category ) || 0 === count( $post_category ) || ! is_array( $post_category ) ) {
  3550. // 'post' requires at least one category.
  3551. if ( 'post' === $post_type && 'auto-draft' !== $post_status ) {
  3552. $post_category = array( get_option( 'default_category' ) );
  3553. } else {
  3554. $post_category = array();
  3555. }
  3556. }
  3557. /*
  3558. * Don't allow contributors to set the post slug for pending review posts.
  3559. *
  3560. * For new posts check the primitive capability, for updates check the meta capability.
  3561. */
  3562. $post_type_object = get_post_type_object( $post_type );
  3563. if ( ! $update && 'pending' === $post_status && ! current_user_can( $post_type_object->cap->publish_posts ) ) {
  3564. $post_name = '';
  3565. } elseif ( $update && 'pending' === $post_status && ! current_user_can( 'publish_post', $post_ID ) ) {
  3566. $post_name = '';
  3567. }
  3568. /*
  3569. * Create a valid post name. Drafts and pending posts are allowed to have
  3570. * an empty post name.
  3571. */
  3572. if ( empty( $post_name ) ) {
  3573. if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true ) ) {
  3574. $post_name = sanitize_title( $post_title );
  3575. } else {
  3576. $post_name = '';
  3577. }
  3578. } else {
  3579. // On updates, we need to check to see if it's using the old, fixed sanitization context.
  3580. $check_name = sanitize_title( $post_name, '', 'old-save' );
  3581. if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
  3582. $post_name = $check_name;
  3583. } else { // new post, or slug has changed.
  3584. $post_name = sanitize_title( $post_name );
  3585. }
  3586. }
  3587. /*
  3588. * Resolve the post date from any provided post date or post date GMT strings;
  3589. * if none are provided, the date will be set to now.
  3590. */
  3591. $post_date = wp_resolve_post_date( $postarr['post_date'], $postarr['post_date_gmt'] );
  3592. if ( ! $post_date ) {
  3593. if ( $wp_error ) {
  3594. return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
  3595. } else {
  3596. return 0;
  3597. }
  3598. }
  3599. if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' === $postarr['post_date_gmt'] ) {
  3600. if ( ! in_array( $post_status, get_post_stati( array( 'date_floating' => true ) ), true ) ) {
  3601. $post_date_gmt = get_gmt_from_date( $post_date );
  3602. } else {
  3603. $post_date_gmt = '0000-00-00 00:00:00';
  3604. }
  3605. } else {
  3606. $post_date_gmt = $postarr['post_date_gmt'];
  3607. }
  3608. if ( $update || '0000-00-00 00:00:00' === $post_date ) {
  3609. $post_modified = current_time( 'mysql' );
  3610. $post_modified_gmt = current_time( 'mysql', 1 );
  3611. } else {
  3612. $post_modified = $post_date;
  3613. $post_modified_gmt = $post_date_gmt;
  3614. }
  3615. if ( 'attachment' !== $post_type ) {
  3616. $now = gmdate( 'Y-m-d H:i:s' );
  3617. if ( 'publish' === $post_status ) {
  3618. if ( strtotime( $post_date_gmt ) - strtotime( $now ) >= MINUTE_IN_SECONDS ) {
  3619. $post_status = 'future';
  3620. }
  3621. } elseif ( 'future' === $post_status ) {
  3622. if ( strtotime( $post_date_gmt ) - strtotime( $now ) < MINUTE_IN_SECONDS ) {
  3623. $post_status = 'publish';
  3624. }
  3625. }
  3626. }
  3627. // Comment status.
  3628. if ( empty( $postarr['comment_status'] ) ) {
  3629. if ( $update ) {
  3630. $comment_status = 'closed';
  3631. } else {
  3632. $comment_status = get_default_comment_status( $post_type );
  3633. }
  3634. } else {
  3635. $comment_status = $postarr['comment_status'];
  3636. }
  3637. // These variables are needed by compact() later.
  3638. $post_content_filtered = $postarr['post_content_filtered'];
  3639. $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
  3640. $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
  3641. $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
  3642. $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
  3643. $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
  3644. /*
  3645. * The 'wp_insert_post_parent' filter expects all variables to be present.
  3646. * Previously, these variables would have already been extracted
  3647. */
  3648. if ( isset( $postarr['menu_order'] ) ) {
  3649. $menu_order = (int) $postarr['menu_order'];
  3650. } else {
  3651. $menu_order = 0;
  3652. }
  3653. $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
  3654. if ( 'private' === $post_status ) {
  3655. $post_password = '';
  3656. }
  3657. if ( isset( $postarr['post_parent'] ) ) {
  3658. $post_parent = (int) $postarr['post_parent'];
  3659. } else {
  3660. $post_parent = 0;
  3661. }
  3662. $new_postarr = array_merge(
  3663. array(
  3664. 'ID' => $post_ID,
  3665. ),
  3666. compact( array_diff( array_keys( $defaults ), array( 'context', 'filter' ) ) )
  3667. );
  3668. /**
  3669. * Filters the post parent -- used to check for and prevent hierarchy loops.
  3670. *
  3671. * @since 3.1.0
  3672. *
  3673. * @param int $post_parent Post parent ID.
  3674. * @param int $post_ID Post ID.
  3675. * @param array $new_postarr Array of parsed post data.
  3676. * @param array $postarr Array of sanitized, but otherwise unmodified post data.
  3677. */
  3678. $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, $new_postarr, $postarr );
  3679. /*
  3680. * If the post is being untrashed and it has a desired slug stored in post meta,
  3681. * reassign it.
  3682. */
  3683. if ( 'trash' === $previous_status && 'trash' !== $post_status ) {
  3684. $desired_post_slug = get_post_meta( $post_ID, '_wp_desired_post_slug', true );
  3685. if ( $desired_post_slug ) {
  3686. delete_post_meta( $post_ID, '_wp_desired_post_slug' );
  3687. $post_name = $desired_post_slug;
  3688. }
  3689. }
  3690. // If a trashed post has the desired slug, change it and let this post have it.
  3691. if ( 'trash' !== $post_status && $post_name ) {
  3692. /**
  3693. * Filters whether or not to add a `__trashed` suffix to trashed posts that match the name of the updated post.
  3694. *
  3695. * @since 5.4.0
  3696. *
  3697. * @param bool $add_trashed_suffix Whether to attempt to add the suffix.
  3698. * @param string $post_name The name of the post being updated.
  3699. * @param int $post_ID Post ID.
  3700. */
  3701. $add_trashed_suffix = apply_filters( 'add_trashed_suffix_to_trashed_posts', true, $post_name, $post_ID );
  3702. if ( $add_trashed_suffix ) {
  3703. wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID );
  3704. }
  3705. }
  3706. // When trashing an existing post, change its slug to allow non-trashed posts to use it.
  3707. if ( 'trash' === $post_status && 'trash' !== $previous_status && 'new' !== $previous_status ) {
  3708. $post_name = wp_add_trashed_suffix_to_post_name_for_post( $post_ID );
  3709. }
  3710. $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
  3711. // Don't unslash.
  3712. $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
  3713. // Expected_slashed (everything!).
  3714. $data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' );
  3715. $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
  3716. foreach ( $emoji_fields as $emoji_field ) {
  3717. if ( isset( $data[ $emoji_field ] ) ) {
  3718. $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
  3719. if ( 'utf8' === $charset ) {
  3720. $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
  3721. }
  3722. }
  3723. }
  3724. if ( 'attachment' === $post_type ) {
  3725. /**
  3726. * Filters attachment post data before it is updated in or added to the database.
  3727. *
  3728. * @since 3.9.0
  3729. * @since 5.4.1 `$unsanitized_postarr` argument added.
  3730. *
  3731. * @param array $data An array of slashed, sanitized, and processed attachment post data.
  3732. * @param array $postarr An array of slashed and sanitized attachment post data, but not processed.
  3733. * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed attachment post data
  3734. * as originally passed to wp_insert_post().
  3735. */
  3736. $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr, $unsanitized_postarr );
  3737. } else {
  3738. /**
  3739. * Filters slashed post data just before it is inserted into the database.
  3740. *
  3741. * @since 2.7.0
  3742. * @since 5.4.1 `$unsanitized_postarr` argument added.
  3743. *
  3744. * @param array $data An array of slashed, sanitized, and processed post data.
  3745. * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
  3746. * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as
  3747. * originally passed to wp_insert_post().
  3748. */
  3749. $data = apply_filters( 'wp_insert_post_data', $data, $postarr, $unsanitized_postarr );
  3750. }
  3751. $data = wp_unslash( $data );
  3752. $where = array( 'ID' => $post_ID );
  3753. if ( $update ) {
  3754. /**
  3755. * Fires immediately before an existing post is updated in the database.
  3756. *
  3757. * @since 2.5.0
  3758. *
  3759. * @param int $post_ID Post ID.
  3760. * @param array $data Array of unslashed post data.
  3761. */
  3762. do_action( 'pre_post_update', $post_ID, $data );
  3763. if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
  3764. if ( $wp_error ) {
  3765. if ( 'attachment' === $post_type ) {
  3766. $message = __( 'Could not update attachment in the database.' );
  3767. } else {
  3768. $message = __( 'Could not update post in the database.' );
  3769. }
  3770. return new WP_Error( 'db_update_error', $message, $wpdb->last_error );
  3771. } else {
  3772. return 0;
  3773. }
  3774. }
  3775. } else {
  3776. // If there is a suggested ID, use it if not already present.
  3777. if ( ! empty( $import_id ) ) {
  3778. $import_id = (int) $import_id;
  3779. if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id ) ) ) {
  3780. $data['ID'] = $import_id;
  3781. }
  3782. }
  3783. if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
  3784. if ( $wp_error ) {
  3785. if ( 'attachment' === $post_type ) {
  3786. $message = __( 'Could not insert attachment into the database.' );
  3787. } else {
  3788. $message = __( 'Could not insert post into the database.' );
  3789. }
  3790. return new WP_Error( 'db_insert_error', $message, $wpdb->last_error );
  3791. } else {
  3792. return 0;
  3793. }
  3794. }
  3795. $post_ID = (int) $wpdb->insert_id;
  3796. // Use the newly generated $post_ID.
  3797. $where = array( 'ID' => $post_ID );
  3798. }
  3799. if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ), true ) ) {
  3800. $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
  3801. $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
  3802. clean_post_cache( $post_ID );
  3803. }
  3804. if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
  3805. wp_set_post_categories( $post_ID, $post_category );
  3806. }
  3807. if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
  3808. wp_set_post_tags( $post_ID, $postarr['tags_input'] );
  3809. }
  3810. // Add default term for all associated custom taxonomies.
  3811. if ( 'auto-draft' !== $post_status ) {
  3812. foreach ( get_object_taxonomies( $post_type, 'object' ) as $taxonomy => $tax_object ) {
  3813. if ( ! empty( $tax_object->default_term ) ) {
  3814. // Filter out empty terms.
  3815. if ( isset( $postarr['tax_input'][ $taxonomy ] ) && is_array( $postarr['tax_input'][ $taxonomy ] ) ) {
  3816. $postarr['tax_input'][ $taxonomy ] = array_filter( $postarr['tax_input'][ $taxonomy ] );
  3817. }
  3818. // Passed custom taxonomy list overwrites the existing list if not empty.
  3819. $terms = wp_get_object_terms( $post_ID, $taxonomy, array( 'fields' => 'ids' ) );
  3820. if ( ! empty( $terms ) && empty( $postarr['tax_input'][ $taxonomy ] ) ) {
  3821. $postarr['tax_input'][ $taxonomy ] = $terms;
  3822. }
  3823. if ( empty( $postarr['tax_input'][ $taxonomy ] ) ) {
  3824. $default_term_id = get_option( 'default_term_' . $taxonomy );
  3825. if ( ! empty( $default_term_id ) ) {
  3826. $postarr['tax_input'][ $taxonomy ] = array( (int) $default_term_id );
  3827. }
  3828. }
  3829. }
  3830. }
  3831. }
  3832. // New-style support for all custom taxonomies.
  3833. if ( ! empty( $postarr['tax_input'] ) ) {
  3834. foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
  3835. $taxonomy_obj = get_taxonomy( $taxonomy );
  3836. if ( ! $taxonomy_obj ) {
  3837. /* translators: %s: Taxonomy name. */
  3838. _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
  3839. continue;
  3840. }
  3841. // array = hierarchical, string = non-hierarchical.
  3842. if ( is_array( $tags ) ) {
  3843. $tags = array_filter( $tags );
  3844. }
  3845. if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
  3846. wp_set_post_terms( $post_ID, $tags, $taxonomy );
  3847. }
  3848. }
  3849. }
  3850. if ( ! empty( $postarr['meta_input'] ) ) {
  3851. foreach ( $postarr['meta_input'] as $field => $value ) {
  3852. update_post_meta( $post_ID, $field, $value );
  3853. }
  3854. }
  3855. $current_guid = get_post_field( 'guid', $post_ID );
  3856. // Set GUID.
  3857. if ( ! $update && '' === $current_guid ) {
  3858. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
  3859. }
  3860. if ( 'attachment' === $postarr['post_type'] ) {
  3861. if ( ! empty( $postarr['file'] ) ) {
  3862. update_attached_file( $post_ID, $postarr['file'] );
  3863. }
  3864. if ( ! empty( $postarr['context'] ) ) {
  3865. add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
  3866. }
  3867. }
  3868. // Set or remove featured image.
  3869. if ( isset( $postarr['_thumbnail_id'] ) ) {
  3870. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) || 'revision' === $post_type;
  3871. if ( ! $thumbnail_support && 'attachment' === $post_type && $post_mime_type ) {
  3872. if ( wp_attachment_is( 'audio', $post_ID ) ) {
  3873. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  3874. } elseif ( wp_attachment_is( 'video', $post_ID ) ) {
  3875. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  3876. }
  3877. }
  3878. if ( $thumbnail_support ) {
  3879. $thumbnail_id = (int) $postarr['_thumbnail_id'];
  3880. if ( -1 === $thumbnail_id ) {
  3881. delete_post_thumbnail( $post_ID );
  3882. } else {
  3883. set_post_thumbnail( $post_ID, $thumbnail_id );
  3884. }
  3885. }
  3886. }
  3887. clean_post_cache( $post_ID );
  3888. $post = get_post( $post_ID );
  3889. if ( ! empty( $postarr['page_template'] ) ) {
  3890. $post->page_template = $postarr['page_template'];
  3891. $page_templates = wp_get_theme()->get_page_templates( $post );
  3892. if ( 'default' !== $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
  3893. if ( $wp_error ) {
  3894. return new WP_Error( 'invalid_page_template', __( 'Invalid page template.' ) );
  3895. }
  3896. update_post_meta( $post_ID, '_wp_page_template', 'default' );
  3897. } else {
  3898. update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
  3899. }
  3900. }
  3901. if ( 'attachment' !== $postarr['post_type'] ) {
  3902. wp_transition_post_status( $data['post_status'], $previous_status, $post );
  3903. } else {
  3904. if ( $update ) {
  3905. /**
  3906. * Fires once an existing attachment has been updated.
  3907. *
  3908. * @since 2.0.0
  3909. *
  3910. * @param int $post_ID Attachment ID.
  3911. */
  3912. do_action( 'edit_attachment', $post_ID );
  3913. $post_after = get_post( $post_ID );
  3914. /**
  3915. * Fires once an existing attachment has been updated.
  3916. *
  3917. * @since 4.4.0
  3918. *
  3919. * @param int $post_ID Post ID.
  3920. * @param WP_Post $post_after Post object following the update.
  3921. * @param WP_Post $post_before Post object before the update.
  3922. */
  3923. do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
  3924. } else {
  3925. /**
  3926. * Fires once an attachment has been added.
  3927. *
  3928. * @since 2.0.0
  3929. *
  3930. * @param int $post_ID Attachment ID.
  3931. */
  3932. do_action( 'add_attachment', $post_ID );
  3933. }
  3934. return $post_ID;
  3935. }
  3936. if ( $update ) {
  3937. /**
  3938. * Fires once an existing post has been updated.
  3939. *
  3940. * The dynamic portion of the hook name, `$post->post_type`, refers to
  3941. * the post type slug.
  3942. *
  3943. * @since 5.1.0
  3944. *
  3945. * @param int $post_ID Post ID.
  3946. * @param WP_Post $post Post object.
  3947. */
  3948. do_action( "edit_post_{$post->post_type}", $post_ID, $post );
  3949. /**
  3950. * Fires once an existing post has been updated.
  3951. *
  3952. * @since 1.2.0
  3953. *
  3954. * @param int $post_ID Post ID.
  3955. * @param WP_Post $post Post object.
  3956. */
  3957. do_action( 'edit_post', $post_ID, $post );
  3958. $post_after = get_post( $post_ID );
  3959. /**
  3960. * Fires once an existing post has been updated.
  3961. *
  3962. * @since 3.0.0
  3963. *
  3964. * @param int $post_ID Post ID.
  3965. * @param WP_Post $post_after Post object following the update.
  3966. * @param WP_Post $post_before Post object before the update.
  3967. */
  3968. do_action( 'post_updated', $post_ID, $post_after, $post_before );
  3969. }
  3970. /**
  3971. * Fires once a post has been saved.
  3972. *
  3973. * The dynamic portion of the hook name, `$post->post_type`, refers to
  3974. * the post type slug.
  3975. *
  3976. * @since 3.7.0
  3977. *
  3978. * @param int $post_ID Post ID.
  3979. * @param WP_Post $post Post object.
  3980. * @param bool $update Whether this is an existing post being updated.
  3981. */
  3982. do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
  3983. /**
  3984. * Fires once a post has been saved.
  3985. *
  3986. * @since 1.5.0
  3987. *
  3988. * @param int $post_ID Post ID.
  3989. * @param WP_Post $post Post object.
  3990. * @param bool $update Whether this is an existing post being updated.
  3991. */
  3992. do_action( 'save_post', $post_ID, $post, $update );
  3993. /**
  3994. * Fires once a post has been saved.
  3995. *
  3996. * @since 2.0.0
  3997. *
  3998. * @param int $post_ID Post ID.
  3999. * @param WP_Post $post Post object.
  4000. * @param bool $update Whether this is an existing post being updated.
  4001. */
  4002. do_action( 'wp_insert_post', $post_ID, $post, $update );
  4003. if ( $fire_after_hooks ) {
  4004. wp_after_insert_post( $post, $update, $post_before );
  4005. }
  4006. return $post_ID;
  4007. }
  4008. /**
  4009. * Update a post with new post data.
  4010. *
  4011. * The date does not have to be set for drafts. You can set the date and it will
  4012. * not be overridden.
  4013. *
  4014. * @since 1.0.0
  4015. * @since 3.5.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
  4016. * @since 5.6.0 Added the `$fire_after_hooks` parameter.
  4017. *
  4018. * @param array|object $postarr Optional. Post data. Arrays are expected to be escaped,
  4019. * objects are not. See wp_insert_post() for accepted arguments.
  4020. * Default array.
  4021. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  4022. * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
  4023. * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
  4024. */
  4025. function wp_update_post( $postarr = array(), $wp_error = false, $fire_after_hooks = true ) {
  4026. if ( is_object( $postarr ) ) {
  4027. // Non-escaped post was passed.
  4028. $postarr = get_object_vars( $postarr );
  4029. $postarr = wp_slash( $postarr );
  4030. }
  4031. // First, get all of the original fields.
  4032. $post = get_post( $postarr['ID'], ARRAY_A );
  4033. if ( is_null( $post ) ) {
  4034. if ( $wp_error ) {
  4035. return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
  4036. }
  4037. return 0;
  4038. }
  4039. // Escape data pulled from DB.
  4040. $post = wp_slash( $post );
  4041. // Passed post category list overwrites existing category list if not empty.
  4042. if ( isset( $postarr['post_category'] ) && is_array( $postarr['post_category'] )
  4043. && count( $postarr['post_category'] ) > 0
  4044. ) {
  4045. $post_cats = $postarr['post_category'];
  4046. } else {
  4047. $post_cats = $post['post_category'];
  4048. }
  4049. // Drafts shouldn't be assigned a date unless explicitly done so by the user.
  4050. if ( isset( $post['post_status'] )
  4051. && in_array( $post['post_status'], array( 'draft', 'pending', 'auto-draft' ), true )
  4052. && empty( $postarr['edit_date'] ) && ( '0000-00-00 00:00:00' === $post['post_date_gmt'] )
  4053. ) {
  4054. $clear_date = true;
  4055. } else {
  4056. $clear_date = false;
  4057. }
  4058. // Merge old and new fields with new fields overwriting old ones.
  4059. $postarr = array_merge( $post, $postarr );
  4060. $postarr['post_category'] = $post_cats;
  4061. if ( $clear_date ) {
  4062. $postarr['post_date'] = current_time( 'mysql' );
  4063. $postarr['post_date_gmt'] = '';
  4064. }
  4065. if ( 'attachment' === $postarr['post_type'] ) {
  4066. return wp_insert_attachment( $postarr, false, 0, $wp_error );
  4067. }
  4068. // Discard 'tags_input' parameter if it's the same as existing post tags.
  4069. if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $postarr['post_type'], 'post_tag' ) ) {
  4070. $tags = get_the_terms( $postarr['ID'], 'post_tag' );
  4071. $tag_names = array();
  4072. if ( $tags && ! is_wp_error( $tags ) ) {
  4073. $tag_names = wp_list_pluck( $tags, 'name' );
  4074. }
  4075. if ( $postarr['tags_input'] === $tag_names ) {
  4076. unset( $postarr['tags_input'] );
  4077. }
  4078. }
  4079. return wp_insert_post( $postarr, $wp_error, $fire_after_hooks );
  4080. }
  4081. /**
  4082. * Publish a post by transitioning the post status.
  4083. *
  4084. * @since 2.1.0
  4085. *
  4086. * @global wpdb $wpdb WordPress database abstraction object.
  4087. *
  4088. * @param int|WP_Post $post Post ID or post object.
  4089. */
  4090. function wp_publish_post( $post ) {
  4091. global $wpdb;
  4092. $post = get_post( $post );
  4093. if ( ! $post ) {
  4094. return;
  4095. }
  4096. if ( 'publish' === $post->post_status ) {
  4097. return;
  4098. }
  4099. $post_before = get_post( $post->ID );
  4100. // Ensure at least one term is applied for taxonomies with a default term.
  4101. foreach ( get_object_taxonomies( $post->post_type, 'object' ) as $taxonomy => $tax_object ) {
  4102. // Skip taxonomy if no default term is set.
  4103. if (
  4104. 'category' !== $taxonomy &&
  4105. empty( $tax_object->default_term )
  4106. ) {
  4107. continue;
  4108. }
  4109. // Do not modify previously set terms.
  4110. if ( ! empty( get_the_terms( $post, $taxonomy ) ) ) {
  4111. continue;
  4112. }
  4113. if ( 'category' === $taxonomy ) {
  4114. $default_term_id = (int) get_option( 'default_category', 0 );
  4115. } else {
  4116. $default_term_id = (int) get_option( 'default_term_' . $taxonomy, 0 );
  4117. }
  4118. if ( ! $default_term_id ) {
  4119. continue;
  4120. }
  4121. wp_set_post_terms( $post->ID, array( $default_term_id ), $taxonomy );
  4122. }
  4123. $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
  4124. clean_post_cache( $post->ID );
  4125. $old_status = $post->post_status;
  4126. $post->post_status = 'publish';
  4127. wp_transition_post_status( 'publish', $old_status, $post );
  4128. /** This action is documented in wp-includes/post.php */
  4129. do_action( "edit_post_{$post->post_type}", $post->ID, $post );
  4130. /** This action is documented in wp-includes/post.php */
  4131. do_action( 'edit_post', $post->ID, $post );
  4132. /** This action is documented in wp-includes/post.php */
  4133. do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
  4134. /** This action is documented in wp-includes/post.php */
  4135. do_action( 'save_post', $post->ID, $post, true );
  4136. /** This action is documented in wp-includes/post.php */
  4137. do_action( 'wp_insert_post', $post->ID, $post, true );
  4138. wp_after_insert_post( $post, true, $post_before );
  4139. }
  4140. /**
  4141. * Publish future post and make sure post ID has future post status.
  4142. *
  4143. * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
  4144. * from publishing drafts, etc.
  4145. *
  4146. * @since 2.5.0
  4147. *
  4148. * @param int|WP_Post $post_id Post ID or post object.
  4149. */
  4150. function check_and_publish_future_post( $post_id ) {
  4151. $post = get_post( $post_id );
  4152. if ( ! $post ) {
  4153. return;
  4154. }
  4155. if ( 'future' !== $post->post_status ) {
  4156. return;
  4157. }
  4158. $time = strtotime( $post->post_date_gmt . ' GMT' );
  4159. // Uh oh, someone jumped the gun!
  4160. if ( $time > time() ) {
  4161. wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // Clear anything else in the system.
  4162. wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
  4163. return;
  4164. }
  4165. // wp_publish_post() returns no meaningful value.
  4166. wp_publish_post( $post_id );
  4167. }
  4168. /**
  4169. * Uses wp_checkdate to return a valid Gregorian-calendar value for post_date.
  4170. * If post_date is not provided, this first checks post_date_gmt if provided,
  4171. * then falls back to use the current time.
  4172. *
  4173. * For back-compat purposes in wp_insert_post, an empty post_date and an invalid
  4174. * post_date_gmt will continue to return '1970-01-01 00:00:00' rather than false.
  4175. *
  4176. * @since 5.7.0
  4177. *
  4178. * @param string $post_date The date in mysql format.
  4179. * @param string $post_date_gmt The GMT date in mysql format.
  4180. * @return string|false A valid Gregorian-calendar date string, or false on failure.
  4181. */
  4182. function wp_resolve_post_date( $post_date = '', $post_date_gmt = '' ) {
  4183. // If the date is empty, set the date to now.
  4184. if ( empty( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
  4185. if ( empty( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
  4186. $post_date = current_time( 'mysql' );
  4187. } else {
  4188. $post_date = get_date_from_gmt( $post_date_gmt );
  4189. }
  4190. }
  4191. // Validate the date.
  4192. $month = substr( $post_date, 5, 2 );
  4193. $day = substr( $post_date, 8, 2 );
  4194. $year = substr( $post_date, 0, 4 );
  4195. $valid_date = wp_checkdate( $month, $day, $year, $post_date );
  4196. if ( ! $valid_date ) {
  4197. return false;
  4198. }
  4199. return $post_date;
  4200. }
  4201. /**
  4202. * Computes a unique slug for the post, when given the desired slug and some post details.
  4203. *
  4204. * @since 2.8.0
  4205. *
  4206. * @global wpdb $wpdb WordPress database abstraction object.
  4207. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  4208. *
  4209. * @param string $slug The desired slug (post_name).
  4210. * @param int $post_ID Post ID.
  4211. * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
  4212. * @param string $post_type Post type.
  4213. * @param int $post_parent Post parent ID.
  4214. * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
  4215. */
  4216. function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
  4217. if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ), true )
  4218. || ( 'inherit' === $post_status && 'revision' === $post_type ) || 'user_request' === $post_type
  4219. ) {
  4220. return $slug;
  4221. }
  4222. /**
  4223. * Filters the post slug before it is generated to be unique.
  4224. *
  4225. * Returning a non-null value will short-circuit the
  4226. * unique slug generation, returning the passed value instead.
  4227. *
  4228. * @since 5.1.0
  4229. *
  4230. * @param string|null $override_slug Short-circuit return value.
  4231. * @param string $slug The desired slug (post_name).
  4232. * @param int $post_ID Post ID.
  4233. * @param string $post_status The post status.
  4234. * @param string $post_type Post type.
  4235. * @param int $post_parent Post parent ID.
  4236. */
  4237. $override_slug = apply_filters( 'pre_wp_unique_post_slug', null, $slug, $post_ID, $post_status, $post_type, $post_parent );
  4238. if ( null !== $override_slug ) {
  4239. return $override_slug;
  4240. }
  4241. global $wpdb, $wp_rewrite;
  4242. $original_slug = $slug;
  4243. $feeds = $wp_rewrite->feeds;
  4244. if ( ! is_array( $feeds ) ) {
  4245. $feeds = array();
  4246. }
  4247. if ( 'attachment' === $post_type ) {
  4248. // Attachment slugs must be unique across all types.
  4249. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
  4250. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
  4251. /**
  4252. * Filters whether the post slug would make a bad attachment slug.
  4253. *
  4254. * @since 3.1.0
  4255. *
  4256. * @param bool $bad_slug Whether the slug would be bad as an attachment slug.
  4257. * @param string $slug The post slug.
  4258. */
  4259. $is_bad_attachment_slug = apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug );
  4260. if ( $post_name_check
  4261. || in_array( $slug, $feeds, true ) || 'embed' === $slug
  4262. || $is_bad_attachment_slug
  4263. ) {
  4264. $suffix = 2;
  4265. do {
  4266. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  4267. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
  4268. $suffix++;
  4269. } while ( $post_name_check );
  4270. $slug = $alt_post_name;
  4271. }
  4272. } elseif ( is_post_type_hierarchical( $post_type ) ) {
  4273. if ( 'nav_menu_item' === $post_type ) {
  4274. return $slug;
  4275. }
  4276. /*
  4277. * Page slugs must be unique within their own trees. Pages are in a separate
  4278. * namespace than posts so page slugs are allowed to overlap post slugs.
  4279. */
  4280. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1";
  4281. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
  4282. /**
  4283. * Filters whether the post slug would make a bad hierarchical post slug.
  4284. *
  4285. * @since 3.1.0
  4286. *
  4287. * @param bool $bad_slug Whether the post slug would be bad in a hierarchical post context.
  4288. * @param string $slug The post slug.
  4289. * @param string $post_type Post type.
  4290. * @param int $post_parent Post parent ID.
  4291. */
  4292. $is_bad_hierarchical_slug = apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent );
  4293. if ( $post_name_check
  4294. || in_array( $slug, $feeds, true ) || 'embed' === $slug
  4295. || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )
  4296. || $is_bad_hierarchical_slug
  4297. ) {
  4298. $suffix = 2;
  4299. do {
  4300. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  4301. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
  4302. $suffix++;
  4303. } while ( $post_name_check );
  4304. $slug = $alt_post_name;
  4305. }
  4306. } else {
  4307. // Post slugs must be unique across all posts.
  4308. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
  4309. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
  4310. $post = get_post( $post_ID );
  4311. // Prevent new post slugs that could result in URLs that conflict with date archives.
  4312. $conflicts_with_date_archive = false;
  4313. if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) ) {
  4314. $slug_num = (int) $slug;
  4315. if ( $slug_num ) {
  4316. $permastructs = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
  4317. $postname_index = array_search( '%postname%', $permastructs, true );
  4318. /*
  4319. * Potential date clashes are as follows:
  4320. *
  4321. * - Any integer in the first permastruct position could be a year.
  4322. * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
  4323. * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
  4324. */
  4325. if ( 0 === $postname_index ||
  4326. ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
  4327. ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
  4328. ) {
  4329. $conflicts_with_date_archive = true;
  4330. }
  4331. }
  4332. }
  4333. /**
  4334. * Filters whether the post slug would be bad as a flat slug.
  4335. *
  4336. * @since 3.1.0
  4337. *
  4338. * @param bool $bad_slug Whether the post slug would be bad as a flat slug.
  4339. * @param string $slug The post slug.
  4340. * @param string $post_type Post type.
  4341. */
  4342. $is_bad_flat_slug = apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type );
  4343. if ( $post_name_check
  4344. || in_array( $slug, $feeds, true ) || 'embed' === $slug
  4345. || $conflicts_with_date_archive
  4346. || $is_bad_flat_slug
  4347. ) {
  4348. $suffix = 2;
  4349. do {
  4350. $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
  4351. $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
  4352. $suffix++;
  4353. } while ( $post_name_check );
  4354. $slug = $alt_post_name;
  4355. }
  4356. }
  4357. /**
  4358. * Filters the unique post slug.
  4359. *
  4360. * @since 3.3.0
  4361. *
  4362. * @param string $slug The post slug.
  4363. * @param int $post_ID Post ID.
  4364. * @param string $post_status The post status.
  4365. * @param string $post_type Post type.
  4366. * @param int $post_parent Post parent ID
  4367. * @param string $original_slug The original post slug.
  4368. */
  4369. return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
  4370. }
  4371. /**
  4372. * Truncate a post slug.
  4373. *
  4374. * @since 3.6.0
  4375. * @access private
  4376. *
  4377. * @see utf8_uri_encode()
  4378. *
  4379. * @param string $slug The slug to truncate.
  4380. * @param int $length Optional. Max length of the slug. Default 200 (characters).
  4381. * @return string The truncated slug.
  4382. */
  4383. function _truncate_post_slug( $slug, $length = 200 ) {
  4384. if ( strlen( $slug ) > $length ) {
  4385. $decoded_slug = urldecode( $slug );
  4386. if ( $decoded_slug === $slug ) {
  4387. $slug = substr( $slug, 0, $length );
  4388. } else {
  4389. $slug = utf8_uri_encode( $decoded_slug, $length );
  4390. }
  4391. }
  4392. return rtrim( $slug, '-' );
  4393. }
  4394. /**
  4395. * Add tags to a post.
  4396. *
  4397. * @see wp_set_post_tags()
  4398. *
  4399. * @since 2.3.0
  4400. *
  4401. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  4402. * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
  4403. * separated by commas. Default empty.
  4404. * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
  4405. */
  4406. function wp_add_post_tags( $post_id = 0, $tags = '' ) {
  4407. return wp_set_post_tags( $post_id, $tags, true );
  4408. }
  4409. /**
  4410. * Set the tags for a post.
  4411. *
  4412. * @since 2.3.0
  4413. *
  4414. * @see wp_set_object_terms()
  4415. *
  4416. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  4417. * @param string|array $tags Optional. An array of tags to set for the post, or a string of tags
  4418. * separated by commas. Default empty.
  4419. * @param bool $append Optional. If true, don't delete existing tags, just add on. If false,
  4420. * replace the tags with the new tags. Default false.
  4421. * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
  4422. */
  4423. function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
  4424. return wp_set_post_terms( $post_id, $tags, 'post_tag', $append );
  4425. }
  4426. /**
  4427. * Set the terms for a post.
  4428. *
  4429. * @since 2.8.0
  4430. *
  4431. * @see wp_set_object_terms()
  4432. *
  4433. * @param int $post_id Optional. The Post ID. Does not default to the ID of the global $post.
  4434. * @param string|array $tags Optional. An array of terms to set for the post, or a string of terms
  4435. * separated by commas. Hierarchical taxonomies must always pass IDs rather
  4436. * than names so that children with the same names but different parents
  4437. * aren't confused. Default empty.
  4438. * @param string $taxonomy Optional. Taxonomy name. Default 'post_tag'.
  4439. * @param bool $append Optional. If true, don't delete existing terms, just add on. If false,
  4440. * replace the terms with the new terms. Default false.
  4441. * @return array|false|WP_Error Array of term taxonomy IDs of affected terms. WP_Error or false on failure.
  4442. */
  4443. function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
  4444. $post_id = (int) $post_id;
  4445. if ( ! $post_id ) {
  4446. return false;
  4447. }
  4448. if ( empty( $tags ) ) {
  4449. $tags = array();
  4450. }
  4451. if ( ! is_array( $tags ) ) {
  4452. $comma = _x( ',', 'tag delimiter' );
  4453. if ( ',' !== $comma ) {
  4454. $tags = str_replace( $comma, ',', $tags );
  4455. }
  4456. $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
  4457. }
  4458. /*
  4459. * Hierarchical taxonomies must always pass IDs rather than names so that
  4460. * children with the same names but different parents aren't confused.
  4461. */
  4462. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  4463. $tags = array_unique( array_map( 'intval', $tags ) );
  4464. }
  4465. return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
  4466. }
  4467. /**
  4468. * Set categories for a post.
  4469. *
  4470. * If no categories are provided, the default category is used.
  4471. *
  4472. * @since 2.1.0
  4473. *
  4474. * @param int $post_ID Optional. The Post ID. Does not default to the ID
  4475. * of the global $post. Default 0.
  4476. * @param int[]|int $post_categories Optional. List of category IDs, or the ID of a single category.
  4477. * Default empty array.
  4478. * @param bool $append If true, don't delete existing categories, just add on.
  4479. * If false, replace the categories with the new categories.
  4480. * @return array|false|WP_Error Array of term taxonomy IDs of affected categories. WP_Error or false on failure.
  4481. */
  4482. function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
  4483. $post_ID = (int) $post_ID;
  4484. $post_type = get_post_type( $post_ID );
  4485. $post_status = get_post_status( $post_ID );
  4486. // If $post_categories isn't already an array, make it one.
  4487. $post_categories = (array) $post_categories;
  4488. if ( empty( $post_categories ) ) {
  4489. /**
  4490. * Filters post types (in addition to 'post') that require a default category.
  4491. *
  4492. * @since 5.5.0
  4493. *
  4494. * @param string[] $post_types An array of post type names. Default empty array.
  4495. */
  4496. $default_category_post_types = apply_filters( 'default_category_post_types', array() );
  4497. // Regular posts always require a default category.
  4498. $default_category_post_types = array_merge( $default_category_post_types, array( 'post' ) );
  4499. if ( in_array( $post_type, $default_category_post_types, true )
  4500. && is_object_in_taxonomy( $post_type, 'category' )
  4501. && 'auto-draft' !== $post_status
  4502. ) {
  4503. $post_categories = array( get_option( 'default_category' ) );
  4504. $append = false;
  4505. } else {
  4506. $post_categories = array();
  4507. }
  4508. } elseif ( 1 === count( $post_categories ) && '' === reset( $post_categories ) ) {
  4509. return true;
  4510. }
  4511. return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
  4512. }
  4513. /**
  4514. * Fires actions related to the transitioning of a post's status.
  4515. *
  4516. * When a post is saved, the post status is "transitioned" from one status to another,
  4517. * though this does not always mean the status has actually changed before and after
  4518. * the save. This function fires a number of action hooks related to that transition:
  4519. * the generic {@see 'transition_post_status'} action, as well as the dynamic hooks
  4520. * {@see '$old_status_to_$new_status'} and {@see '$new_status_$post->post_type'}. Note
  4521. * that the function does not transition the post object in the database.
  4522. *
  4523. * For instance: When publishing a post for the first time, the post status may transition
  4524. * from 'draft' – or some other status – to 'publish'. However, if a post is already
  4525. * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
  4526. * before and after the transition.
  4527. *
  4528. * @since 2.3.0
  4529. *
  4530. * @param string $new_status Transition to this post status.
  4531. * @param string $old_status Previous post status.
  4532. * @param WP_Post $post Post data.
  4533. */
  4534. function wp_transition_post_status( $new_status, $old_status, $post ) {
  4535. /**
  4536. * Fires when a post is transitioned from one status to another.
  4537. *
  4538. * @since 2.3.0
  4539. *
  4540. * @param string $new_status New post status.
  4541. * @param string $old_status Old post status.
  4542. * @param WP_Post $post Post object.
  4543. */
  4544. do_action( 'transition_post_status', $new_status, $old_status, $post );
  4545. /**
  4546. * Fires when a post is transitioned from one status to another.
  4547. *
  4548. * The dynamic portions of the hook name, `$new_status` and `$old_status`,
  4549. * refer to the old and new post statuses, respectively.
  4550. *
  4551. * @since 2.3.0
  4552. *
  4553. * @param WP_Post $post Post object.
  4554. */
  4555. do_action( "{$old_status}_to_{$new_status}", $post );
  4556. /**
  4557. * Fires when a post is transitioned from one status to another.
  4558. *
  4559. * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
  4560. * refer to the new post status and post type, respectively.
  4561. *
  4562. * Possible hook names include:
  4563. *
  4564. * - `draft_post`
  4565. * - `future_post`
  4566. * - `pending_post`
  4567. * - `private_post`
  4568. * - `publish_post`
  4569. * - `trash_post`
  4570. * - `draft_page`
  4571. * - `future_page`
  4572. * - `pending_page`
  4573. * - `private_page`
  4574. * - `publish_page`
  4575. * - `trash_page`
  4576. * - `publish_attachment`
  4577. * - `trash_attachment`
  4578. *
  4579. * Please note: When this action is hooked using a particular post status (like
  4580. * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
  4581. * first transitioned to that status from something else, as well as upon
  4582. * subsequent post updates (old and new status are both the same).
  4583. *
  4584. * Therefore, if you are looking to only fire a callback when a post is first
  4585. * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
  4586. *
  4587. * @since 2.3.0
  4588. *
  4589. * @param int $post_id Post ID.
  4590. * @param WP_Post $post Post object.
  4591. */
  4592. do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
  4593. }
  4594. /**
  4595. * Fires actions after a post, its terms and meta data has been saved.
  4596. *
  4597. * @since 5.6.0
  4598. *
  4599. * @param int|WP_Post $post The post ID or object that has been saved.
  4600. * @param bool $update Whether this is an existing post being updated.
  4601. * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
  4602. * to the update for updated posts.
  4603. */
  4604. function wp_after_insert_post( $post, $update, $post_before ) {
  4605. $post = get_post( $post );
  4606. if ( ! $post ) {
  4607. return;
  4608. }
  4609. $post_id = $post->ID;
  4610. /**
  4611. * Fires once a post, its terms and meta data has been saved.
  4612. *
  4613. * @since 5.6.0
  4614. *
  4615. * @param int $post_id Post ID.
  4616. * @param WP_Post $post Post object.
  4617. * @param bool $update Whether this is an existing post being updated.
  4618. * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior
  4619. * to the update for updated posts.
  4620. */
  4621. do_action( 'wp_after_insert_post', $post_id, $post, $update, $post_before );
  4622. }
  4623. //
  4624. // Comment, trackback, and pingback functions.
  4625. //
  4626. /**
  4627. * Add a URL to those already pinged.
  4628. *
  4629. * @since 1.5.0
  4630. * @since 4.7.0 `$post_id` can be a WP_Post object.
  4631. * @since 4.7.0 `$uri` can be an array of URIs.
  4632. *
  4633. * @global wpdb $wpdb WordPress database abstraction object.
  4634. *
  4635. * @param int|WP_Post $post_id Post object or ID.
  4636. * @param string|array $uri Ping URI or array of URIs.
  4637. * @return int|false How many rows were updated.
  4638. */
  4639. function add_ping( $post_id, $uri ) {
  4640. global $wpdb;
  4641. $post = get_post( $post_id );
  4642. if ( ! $post ) {
  4643. return false;
  4644. }
  4645. $pung = trim( $post->pinged );
  4646. $pung = preg_split( '/\s/', $pung );
  4647. if ( is_array( $uri ) ) {
  4648. $pung = array_merge( $pung, $uri );
  4649. } else {
  4650. $pung[] = $uri;
  4651. }
  4652. $new = implode( "\n", $pung );
  4653. /**
  4654. * Filters the new ping URL to add for the given post.
  4655. *
  4656. * @since 2.0.0
  4657. *
  4658. * @param string $new New ping URL to add.
  4659. */
  4660. $new = apply_filters( 'add_ping', $new );
  4661. $return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
  4662. clean_post_cache( $post->ID );
  4663. return $return;
  4664. }
  4665. /**
  4666. * Retrieve enclosures already enclosed for a post.
  4667. *
  4668. * @since 1.5.0
  4669. *
  4670. * @param int $post_id Post ID.
  4671. * @return string[] Array of enclosures for the given post.
  4672. */
  4673. function get_enclosed( $post_id ) {
  4674. $custom_fields = get_post_custom( $post_id );
  4675. $pung = array();
  4676. if ( ! is_array( $custom_fields ) ) {
  4677. return $pung;
  4678. }
  4679. foreach ( $custom_fields as $key => $val ) {
  4680. if ( 'enclosure' !== $key || ! is_array( $val ) ) {
  4681. continue;
  4682. }
  4683. foreach ( $val as $enc ) {
  4684. $enclosure = explode( "\n", $enc );
  4685. $pung[] = trim( $enclosure[0] );
  4686. }
  4687. }
  4688. /**
  4689. * Filters the list of enclosures already enclosed for the given post.
  4690. *
  4691. * @since 2.0.0
  4692. *
  4693. * @param string[] $pung Array of enclosures for the given post.
  4694. * @param int $post_id Post ID.
  4695. */
  4696. return apply_filters( 'get_enclosed', $pung, $post_id );
  4697. }
  4698. /**
  4699. * Retrieve URLs already pinged for a post.
  4700. *
  4701. * @since 1.5.0
  4702. *
  4703. * @since 4.7.0 `$post_id` can be a WP_Post object.
  4704. *
  4705. * @param int|WP_Post $post_id Post ID or object.
  4706. * @return string[]|false Array of URLs already pinged for the given post, false if the post is not found.
  4707. */
  4708. function get_pung( $post_id ) {
  4709. $post = get_post( $post_id );
  4710. if ( ! $post ) {
  4711. return false;
  4712. }
  4713. $pung = trim( $post->pinged );
  4714. $pung = preg_split( '/\s/', $pung );
  4715. /**
  4716. * Filters the list of already-pinged URLs for the given post.
  4717. *
  4718. * @since 2.0.0
  4719. *
  4720. * @param string[] $pung Array of URLs already pinged for the given post.
  4721. */
  4722. return apply_filters( 'get_pung', $pung );
  4723. }
  4724. /**
  4725. * Retrieve URLs that need to be pinged.
  4726. *
  4727. * @since 1.5.0
  4728. * @since 4.7.0 `$post_id` can be a WP_Post object.
  4729. *
  4730. * @param int|WP_Post $post_id Post Object or ID
  4731. * @return string[]|false List of URLs yet to ping.
  4732. */
  4733. function get_to_ping( $post_id ) {
  4734. $post = get_post( $post_id );
  4735. if ( ! $post ) {
  4736. return false;
  4737. }
  4738. $to_ping = sanitize_trackback_urls( $post->to_ping );
  4739. $to_ping = preg_split( '/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY );
  4740. /**
  4741. * Filters the list of URLs yet to ping for the given post.
  4742. *
  4743. * @since 2.0.0
  4744. *
  4745. * @param string[] $to_ping List of URLs yet to ping.
  4746. */
  4747. return apply_filters( 'get_to_ping', $to_ping );
  4748. }
  4749. /**
  4750. * Do trackbacks for a list of URLs.
  4751. *
  4752. * @since 1.0.0
  4753. *
  4754. * @param string $tb_list Comma separated list of URLs.
  4755. * @param int $post_id Post ID.
  4756. */
  4757. function trackback_url_list( $tb_list, $post_id ) {
  4758. if ( ! empty( $tb_list ) ) {
  4759. // Get post data.
  4760. $postdata = get_post( $post_id, ARRAY_A );
  4761. // Form an excerpt.
  4762. $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
  4763. if ( strlen( $excerpt ) > 255 ) {
  4764. $excerpt = substr( $excerpt, 0, 252 ) . '&hellip;';
  4765. }
  4766. $trackback_urls = explode( ',', $tb_list );
  4767. foreach ( (array) $trackback_urls as $tb_url ) {
  4768. $tb_url = trim( $tb_url );
  4769. trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
  4770. }
  4771. }
  4772. }
  4773. //
  4774. // Page functions.
  4775. //
  4776. /**
  4777. * Get a list of page IDs.
  4778. *
  4779. * @since 2.0.0
  4780. *
  4781. * @global wpdb $wpdb WordPress database abstraction object.
  4782. *
  4783. * @return string[] List of page IDs as strings.
  4784. */
  4785. function get_all_page_ids() {
  4786. global $wpdb;
  4787. $page_ids = wp_cache_get( 'all_page_ids', 'posts' );
  4788. if ( ! is_array( $page_ids ) ) {
  4789. $page_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'" );
  4790. wp_cache_add( 'all_page_ids', $page_ids, 'posts' );
  4791. }
  4792. return $page_ids;
  4793. }
  4794. /**
  4795. * Retrieves page data given a page ID or page object.
  4796. *
  4797. * Use get_post() instead of get_page().
  4798. *
  4799. * @since 1.5.1
  4800. * @deprecated 3.5.0 Use get_post()
  4801. *
  4802. * @param int|WP_Post $page Page object or page ID. Passed by reference.
  4803. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  4804. * correspond to a WP_Post object, an associative array, or a numeric array,
  4805. * respectively. Default OBJECT.
  4806. * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
  4807. * 'edit', 'db', 'display'. Default 'raw'.
  4808. * @return WP_Post|array|null WP_Post or array on success, null on failure.
  4809. */
  4810. function get_page( $page, $output = OBJECT, $filter = 'raw' ) {
  4811. return get_post( $page, $output, $filter );
  4812. }
  4813. /**
  4814. * Retrieves a page given its path.
  4815. *
  4816. * @since 2.1.0
  4817. *
  4818. * @global wpdb $wpdb WordPress database abstraction object.
  4819. *
  4820. * @param string $page_path Page path.
  4821. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  4822. * correspond to a WP_Post object, an associative array, or a numeric array,
  4823. * respectively. Default OBJECT.
  4824. * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
  4825. * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
  4826. */
  4827. function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
  4828. global $wpdb;
  4829. $last_changed = wp_cache_get_last_changed( 'posts' );
  4830. $hash = md5( $page_path . serialize( $post_type ) );
  4831. $cache_key = "get_page_by_path:$hash:$last_changed";
  4832. $cached = wp_cache_get( $cache_key, 'posts' );
  4833. if ( false !== $cached ) {
  4834. // Special case: '0' is a bad `$page_path`.
  4835. if ( '0' === $cached || 0 === $cached ) {
  4836. return;
  4837. } else {
  4838. return get_post( $cached, $output );
  4839. }
  4840. }
  4841. $page_path = rawurlencode( urldecode( $page_path ) );
  4842. $page_path = str_replace( '%2F', '/', $page_path );
  4843. $page_path = str_replace( '%20', ' ', $page_path );
  4844. $parts = explode( '/', trim( $page_path, '/' ) );
  4845. $parts = array_map( 'sanitize_title_for_query', $parts );
  4846. $escaped_parts = esc_sql( $parts );
  4847. $in_string = "'" . implode( "','", $escaped_parts ) . "'";
  4848. if ( is_array( $post_type ) ) {
  4849. $post_types = $post_type;
  4850. } else {
  4851. $post_types = array( $post_type, 'attachment' );
  4852. }
  4853. $post_types = esc_sql( $post_types );
  4854. $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
  4855. $sql = "
  4856. SELECT ID, post_name, post_parent, post_type
  4857. FROM $wpdb->posts
  4858. WHERE post_name IN ($in_string)
  4859. AND post_type IN ($post_type_in_string)
  4860. ";
  4861. $pages = $wpdb->get_results( $sql, OBJECT_K );
  4862. $revparts = array_reverse( $parts );
  4863. $foundid = 0;
  4864. foreach ( (array) $pages as $page ) {
  4865. if ( $page->post_name == $revparts[0] ) {
  4866. $count = 0;
  4867. $p = $page;
  4868. /*
  4869. * Loop through the given path parts from right to left,
  4870. * ensuring each matches the post ancestry.
  4871. */
  4872. while ( 0 != $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
  4873. $count++;
  4874. $parent = $pages[ $p->post_parent ];
  4875. if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] ) {
  4876. break;
  4877. }
  4878. $p = $parent;
  4879. }
  4880. if ( 0 == $p->post_parent && count( $revparts ) == $count + 1 && $p->post_name == $revparts[ $count ] ) {
  4881. $foundid = $page->ID;
  4882. if ( $page->post_type == $post_type ) {
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. }
  4888. // We cache misses as well as hits.
  4889. wp_cache_set( $cache_key, $foundid, 'posts' );
  4890. if ( $foundid ) {
  4891. return get_post( $foundid, $output );
  4892. }
  4893. }
  4894. /**
  4895. * Retrieve a page given its title.
  4896. *
  4897. * If more than one post uses the same title, the post with the smallest ID will be returned.
  4898. * Be careful: in case of more than one post having the same title, it will check the oldest
  4899. * publication date, not the smallest ID.
  4900. *
  4901. * Because this function uses the MySQL '=' comparison, $page_title will usually be matched
  4902. * as case-insensitive with default collation.
  4903. *
  4904. * @since 2.1.0
  4905. * @since 3.0.0 The `$post_type` parameter was added.
  4906. *
  4907. * @global wpdb $wpdb WordPress database abstraction object.
  4908. *
  4909. * @param string $page_title Page title.
  4910. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  4911. * correspond to a WP_Post object, an associative array, or a numeric array,
  4912. * respectively. Default OBJECT.
  4913. * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
  4914. * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
  4915. */
  4916. function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
  4917. global $wpdb;
  4918. if ( is_array( $post_type ) ) {
  4919. $post_type = esc_sql( $post_type );
  4920. $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
  4921. $sql = $wpdb->prepare(
  4922. "
  4923. SELECT ID
  4924. FROM $wpdb->posts
  4925. WHERE post_title = %s
  4926. AND post_type IN ($post_type_in_string)
  4927. ",
  4928. $page_title
  4929. );
  4930. } else {
  4931. $sql = $wpdb->prepare(
  4932. "
  4933. SELECT ID
  4934. FROM $wpdb->posts
  4935. WHERE post_title = %s
  4936. AND post_type = %s
  4937. ",
  4938. $page_title,
  4939. $post_type
  4940. );
  4941. }
  4942. $page = $wpdb->get_var( $sql );
  4943. if ( $page ) {
  4944. return get_post( $page, $output );
  4945. }
  4946. }
  4947. /**
  4948. * Identify descendants of a given page ID in a list of page objects.
  4949. *
  4950. * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
  4951. *
  4952. * @since 1.5.1
  4953. *
  4954. * @param int $page_id Page ID.
  4955. * @param array $pages List of page objects from which descendants should be identified.
  4956. * @return array List of page children.
  4957. */
  4958. function get_page_children( $page_id, $pages ) {
  4959. // Build a hash of ID -> children.
  4960. $children = array();
  4961. foreach ( (array) $pages as $page ) {
  4962. $children[ (int) $page->post_parent ][] = $page;
  4963. }
  4964. $page_list = array();
  4965. // Start the search by looking at immediate children.
  4966. if ( isset( $children[ $page_id ] ) ) {
  4967. // Always start at the end of the stack in order to preserve original `$pages` order.
  4968. $to_look = array_reverse( $children[ $page_id ] );
  4969. while ( $to_look ) {
  4970. $p = array_pop( $to_look );
  4971. $page_list[] = $p;
  4972. if ( isset( $children[ $p->ID ] ) ) {
  4973. foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
  4974. // Append to the `$to_look` stack to descend the tree.
  4975. $to_look[] = $child;
  4976. }
  4977. }
  4978. }
  4979. }
  4980. return $page_list;
  4981. }
  4982. /**
  4983. * Order the pages with children under parents in a flat list.
  4984. *
  4985. * It uses auxiliary structure to hold parent-children relationships and
  4986. * runs in O(N) complexity
  4987. *
  4988. * @since 2.0.0
  4989. *
  4990. * @param WP_Post[] $pages Posts array (passed by reference).
  4991. * @param int $page_id Optional. Parent page ID. Default 0.
  4992. * @return string[] Array of post names keyed by ID and arranged by hierarchy. Children immediately follow their parents.
  4993. */
  4994. function get_page_hierarchy( &$pages, $page_id = 0 ) {
  4995. if ( empty( $pages ) ) {
  4996. return array();
  4997. }
  4998. $children = array();
  4999. foreach ( (array) $pages as $p ) {
  5000. $parent_id = (int) $p->post_parent;
  5001. $children[ $parent_id ][] = $p;
  5002. }
  5003. $result = array();
  5004. _page_traverse_name( $page_id, $children, $result );
  5005. return $result;
  5006. }
  5007. /**
  5008. * Traverse and return all the nested children post names of a root page.
  5009. *
  5010. * $children contains parent-children relations
  5011. *
  5012. * @since 2.9.0
  5013. * @access private
  5014. *
  5015. * @see _page_traverse_name()
  5016. *
  5017. * @param int $page_id Page ID.
  5018. * @param array $children Parent-children relations (passed by reference).
  5019. * @param string[] $result Array of page names keyed by ID (passed by reference).
  5020. */
  5021. function _page_traverse_name( $page_id, &$children, &$result ) {
  5022. if ( isset( $children[ $page_id ] ) ) {
  5023. foreach ( (array) $children[ $page_id ] as $child ) {
  5024. $result[ $child->ID ] = $child->post_name;
  5025. _page_traverse_name( $child->ID, $children, $result );
  5026. }
  5027. }
  5028. }
  5029. /**
  5030. * Build the URI path for a page.
  5031. *
  5032. * Sub pages will be in the "directory" under the parent page post name.
  5033. *
  5034. * @since 1.5.0
  5035. * @since 4.6.0 The `$page` parameter was made optional.
  5036. *
  5037. * @param WP_Post|object|int $page Optional. Page ID or WP_Post object. Default is global $post.
  5038. * @return string|false Page URI, false on error.
  5039. */
  5040. function get_page_uri( $page = 0 ) {
  5041. if ( ! $page instanceof WP_Post ) {
  5042. $page = get_post( $page );
  5043. }
  5044. if ( ! $page ) {
  5045. return false;
  5046. }
  5047. $uri = $page->post_name;
  5048. foreach ( $page->ancestors as $parent ) {
  5049. $parent = get_post( $parent );
  5050. if ( $parent && $parent->post_name ) {
  5051. $uri = $parent->post_name . '/' . $uri;
  5052. }
  5053. }
  5054. /**
  5055. * Filters the URI for a page.
  5056. *
  5057. * @since 4.4.0
  5058. *
  5059. * @param string $uri Page URI.
  5060. * @param WP_Post $page Page object.
  5061. */
  5062. return apply_filters( 'get_page_uri', $uri, $page );
  5063. }
  5064. /**
  5065. * Retrieve an array of pages (or hierarchical post type items).
  5066. *
  5067. * @global wpdb $wpdb WordPress database abstraction object.
  5068. *
  5069. * @since 1.5.0
  5070. *
  5071. * @param array|string $args {
  5072. * Optional. Array or string of arguments to retrieve pages.
  5073. *
  5074. * @type int $child_of Page ID to return child and grandchild pages of. Note: The value
  5075. * of `$hierarchical` has no bearing on whether `$child_of` returns
  5076. * hierarchical results. Default 0, or no restriction.
  5077. * @type string $sort_order How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
  5078. * @type string $sort_column What columns to sort pages by, comma-separated. Accepts 'post_author',
  5079. * 'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
  5080. * 'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
  5081. * 'post_' can be omitted for any values that start with it.
  5082. * Default 'post_title'.
  5083. * @type bool $hierarchical Whether to return pages hierarchically. If false in conjunction with
  5084. * `$child_of` also being false, both arguments will be disregarded.
  5085. * Default true.
  5086. * @type int[] $exclude Array of page IDs to exclude. Default empty array.
  5087. * @type int[] $include Array of page IDs to include. Cannot be used with `$child_of`,
  5088. * `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
  5089. * Default empty array.
  5090. * @type string $meta_key Only include pages with this meta key. Default empty.
  5091. * @type string $meta_value Only include pages with this meta value. Requires `$meta_key`.
  5092. * Default empty.
  5093. * @type string $authors A comma-separated list of author IDs. Default empty.
  5094. * @type int $parent Page ID to return direct children of. Default -1, or no restriction.
  5095. * @type string|int[] $exclude_tree Comma-separated string or array of page IDs to exclude.
  5096. * Default empty array.
  5097. * @type int $number The number of pages to return. Default 0, or all pages.
  5098. * @type int $offset The number of pages to skip before returning. Requires `$number`.
  5099. * Default 0.
  5100. * @type string $post_type The post type to query. Default 'page'.
  5101. * @type string|array $post_status A comma-separated list or array of post statuses to include.
  5102. * Default 'publish'.
  5103. * }
  5104. * @return WP_Post[]|int[]|false Array of pages (or hierarchical post type items). Boolean false if the
  5105. * specified post type is not hierarchical or the specified status is not
  5106. * supported by the post type.
  5107. */
  5108. function get_pages( $args = array() ) {
  5109. global $wpdb;
  5110. $defaults = array(
  5111. 'child_of' => 0,
  5112. 'sort_order' => 'ASC',
  5113. 'sort_column' => 'post_title',
  5114. 'hierarchical' => 1,
  5115. 'exclude' => array(),
  5116. 'include' => array(),
  5117. 'meta_key' => '',
  5118. 'meta_value' => '',
  5119. 'authors' => '',
  5120. 'parent' => -1,
  5121. 'exclude_tree' => array(),
  5122. 'number' => '',
  5123. 'offset' => 0,
  5124. 'post_type' => 'page',
  5125. 'post_status' => 'publish',
  5126. );
  5127. $parsed_args = wp_parse_args( $args, $defaults );
  5128. $number = (int) $parsed_args['number'];
  5129. $offset = (int) $parsed_args['offset'];
  5130. $child_of = (int) $parsed_args['child_of'];
  5131. $hierarchical = $parsed_args['hierarchical'];
  5132. $exclude = $parsed_args['exclude'];
  5133. $meta_key = $parsed_args['meta_key'];
  5134. $meta_value = $parsed_args['meta_value'];
  5135. $parent = $parsed_args['parent'];
  5136. $post_status = $parsed_args['post_status'];
  5137. // Make sure the post type is hierarchical.
  5138. $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
  5139. if ( ! in_array( $parsed_args['post_type'], $hierarchical_post_types, true ) ) {
  5140. return false;
  5141. }
  5142. if ( $parent > 0 && ! $child_of ) {
  5143. $hierarchical = false;
  5144. }
  5145. // Make sure we have a valid post status.
  5146. if ( ! is_array( $post_status ) ) {
  5147. $post_status = explode( ',', $post_status );
  5148. }
  5149. if ( array_diff( $post_status, get_post_stati() ) ) {
  5150. return false;
  5151. }
  5152. // $args can be whatever, only use the args defined in defaults to compute the key.
  5153. $key = md5( serialize( wp_array_slice_assoc( $parsed_args, array_keys( $defaults ) ) ) );
  5154. $last_changed = wp_cache_get_last_changed( 'posts' );
  5155. $cache_key = "get_pages:$key:$last_changed";
  5156. $cache = wp_cache_get( $cache_key, 'posts' );
  5157. if ( false !== $cache ) {
  5158. _prime_post_caches( $cache, false, false );
  5159. // Convert to WP_Post instances.
  5160. $pages = array_map( 'get_post', $cache );
  5161. /** This filter is documented in wp-includes/post.php */
  5162. $pages = apply_filters( 'get_pages', $pages, $parsed_args );
  5163. return $pages;
  5164. }
  5165. $inclusions = '';
  5166. if ( ! empty( $parsed_args['include'] ) ) {
  5167. $child_of = 0; // Ignore child_of, parent, exclude, meta_key, and meta_value params if using include.
  5168. $parent = -1;
  5169. $exclude = '';
  5170. $meta_key = '';
  5171. $meta_value = '';
  5172. $hierarchical = false;
  5173. $incpages = wp_parse_id_list( $parsed_args['include'] );
  5174. if ( ! empty( $incpages ) ) {
  5175. $inclusions = ' AND ID IN (' . implode( ',', $incpages ) . ')';
  5176. }
  5177. }
  5178. $exclusions = '';
  5179. if ( ! empty( $exclude ) ) {
  5180. $expages = wp_parse_id_list( $exclude );
  5181. if ( ! empty( $expages ) ) {
  5182. $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) . ')';
  5183. }
  5184. }
  5185. $author_query = '';
  5186. if ( ! empty( $parsed_args['authors'] ) ) {
  5187. $post_authors = wp_parse_list( $parsed_args['authors'] );
  5188. if ( ! empty( $post_authors ) ) {
  5189. foreach ( $post_authors as $post_author ) {
  5190. // Do we have an author id or an author login?
  5191. if ( 0 == (int) $post_author ) {
  5192. $post_author = get_user_by( 'login', $post_author );
  5193. if ( empty( $post_author ) ) {
  5194. continue;
  5195. }
  5196. if ( empty( $post_author->ID ) ) {
  5197. continue;
  5198. }
  5199. $post_author = $post_author->ID;
  5200. }
  5201. if ( '' === $author_query ) {
  5202. $author_query = $wpdb->prepare( ' post_author = %d ', $post_author );
  5203. } else {
  5204. $author_query .= $wpdb->prepare( ' OR post_author = %d ', $post_author );
  5205. }
  5206. }
  5207. if ( '' !== $author_query ) {
  5208. $author_query = " AND ($author_query)";
  5209. }
  5210. }
  5211. }
  5212. $join = '';
  5213. $where = "$exclusions $inclusions ";
  5214. if ( '' !== $meta_key || '' !== $meta_value ) {
  5215. $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
  5216. // meta_key and meta_value might be slashed.
  5217. $meta_key = wp_unslash( $meta_key );
  5218. $meta_value = wp_unslash( $meta_value );
  5219. if ( '' !== $meta_key ) {
  5220. $where .= $wpdb->prepare( " AND $wpdb->postmeta.meta_key = %s", $meta_key );
  5221. }
  5222. if ( '' !== $meta_value ) {
  5223. $where .= $wpdb->prepare( " AND $wpdb->postmeta.meta_value = %s", $meta_value );
  5224. }
  5225. }
  5226. if ( is_array( $parent ) ) {
  5227. $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
  5228. if ( ! empty( $post_parent__in ) ) {
  5229. $where .= " AND post_parent IN ($post_parent__in)";
  5230. }
  5231. } elseif ( $parent >= 0 ) {
  5232. $where .= $wpdb->prepare( ' AND post_parent = %d ', $parent );
  5233. }
  5234. if ( 1 === count( $post_status ) ) {
  5235. $where_post_type = $wpdb->prepare( 'post_type = %s AND post_status = %s', $parsed_args['post_type'], reset( $post_status ) );
  5236. } else {
  5237. $post_status = implode( "', '", $post_status );
  5238. $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $parsed_args['post_type'] );
  5239. }
  5240. $orderby_array = array();
  5241. $allowed_keys = array(
  5242. 'author',
  5243. 'post_author',
  5244. 'date',
  5245. 'post_date',
  5246. 'title',
  5247. 'post_title',
  5248. 'name',
  5249. 'post_name',
  5250. 'modified',
  5251. 'post_modified',
  5252. 'modified_gmt',
  5253. 'post_modified_gmt',
  5254. 'menu_order',
  5255. 'parent',
  5256. 'post_parent',
  5257. 'ID',
  5258. 'rand',
  5259. 'comment_count',
  5260. );
  5261. foreach ( explode( ',', $parsed_args['sort_column'] ) as $orderby ) {
  5262. $orderby = trim( $orderby );
  5263. if ( ! in_array( $orderby, $allowed_keys, true ) ) {
  5264. continue;
  5265. }
  5266. switch ( $orderby ) {
  5267. case 'menu_order':
  5268. break;
  5269. case 'ID':
  5270. $orderby = "$wpdb->posts.ID";
  5271. break;
  5272. case 'rand':
  5273. $orderby = 'RAND()';
  5274. break;
  5275. case 'comment_count':
  5276. $orderby = "$wpdb->posts.comment_count";
  5277. break;
  5278. default:
  5279. if ( 0 === strpos( $orderby, 'post_' ) ) {
  5280. $orderby = "$wpdb->posts." . $orderby;
  5281. } else {
  5282. $orderby = "$wpdb->posts.post_" . $orderby;
  5283. }
  5284. }
  5285. $orderby_array[] = $orderby;
  5286. }
  5287. $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
  5288. $sort_order = strtoupper( $parsed_args['sort_order'] );
  5289. if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ), true ) ) {
  5290. $sort_order = 'ASC';
  5291. }
  5292. $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
  5293. $query .= $author_query;
  5294. $query .= ' ORDER BY ' . $sort_column . ' ' . $sort_order;
  5295. if ( ! empty( $number ) ) {
  5296. $query .= ' LIMIT ' . $offset . ',' . $number;
  5297. }
  5298. $pages = $wpdb->get_results( $query );
  5299. if ( empty( $pages ) ) {
  5300. wp_cache_set( $cache_key, array(), 'posts' );
  5301. /** This filter is documented in wp-includes/post.php */
  5302. $pages = apply_filters( 'get_pages', array(), $parsed_args );
  5303. return $pages;
  5304. }
  5305. // Sanitize before caching so it'll only get done once.
  5306. $num_pages = count( $pages );
  5307. for ( $i = 0; $i < $num_pages; $i++ ) {
  5308. $pages[ $i ] = sanitize_post( $pages[ $i ], 'raw' );
  5309. }
  5310. // Update cache.
  5311. update_post_cache( $pages );
  5312. if ( $child_of || $hierarchical ) {
  5313. $pages = get_page_children( $child_of, $pages );
  5314. }
  5315. if ( ! empty( $parsed_args['exclude_tree'] ) ) {
  5316. $exclude = wp_parse_id_list( $parsed_args['exclude_tree'] );
  5317. foreach ( $exclude as $id ) {
  5318. $children = get_page_children( $id, $pages );
  5319. foreach ( $children as $child ) {
  5320. $exclude[] = $child->ID;
  5321. }
  5322. }
  5323. $num_pages = count( $pages );
  5324. for ( $i = 0; $i < $num_pages; $i++ ) {
  5325. if ( in_array( $pages[ $i ]->ID, $exclude, true ) ) {
  5326. unset( $pages[ $i ] );
  5327. }
  5328. }
  5329. }
  5330. $page_structure = array();
  5331. foreach ( $pages as $page ) {
  5332. $page_structure[] = $page->ID;
  5333. }
  5334. wp_cache_set( $cache_key, $page_structure, 'posts' );
  5335. // Convert to WP_Post instances.
  5336. $pages = array_map( 'get_post', $pages );
  5337. /**
  5338. * Filters the retrieved list of pages.
  5339. *
  5340. * @since 2.1.0
  5341. *
  5342. * @param WP_Post[] $pages Array of page objects.
  5343. * @param array $parsed_args Array of get_pages() arguments.
  5344. */
  5345. return apply_filters( 'get_pages', $pages, $parsed_args );
  5346. }
  5347. //
  5348. // Attachment functions.
  5349. //
  5350. /**
  5351. * Determines whether an attachment URI is local and really an attachment.
  5352. *
  5353. * For more information on this and similar theme functions, check out
  5354. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  5355. * Conditional Tags} article in the Theme Developer Handbook.
  5356. *
  5357. * @since 2.0.0
  5358. *
  5359. * @param string $url URL to check
  5360. * @return bool True on success, false on failure.
  5361. */
  5362. function is_local_attachment( $url ) {
  5363. if ( strpos( $url, home_url() ) === false ) {
  5364. return false;
  5365. }
  5366. if ( strpos( $url, home_url( '/?attachment_id=' ) ) !== false ) {
  5367. return true;
  5368. }
  5369. $id = url_to_postid( $url );
  5370. if ( $id ) {
  5371. $post = get_post( $id );
  5372. if ( 'attachment' === $post->post_type ) {
  5373. return true;
  5374. }
  5375. }
  5376. return false;
  5377. }
  5378. /**
  5379. * Insert an attachment.
  5380. *
  5381. * If you set the 'ID' in the $args parameter, it will mean that you are
  5382. * updating and attempt to update the attachment. You can also set the
  5383. * attachment name or title by setting the key 'post_name' or 'post_title'.
  5384. *
  5385. * You can set the dates for the attachment manually by setting the 'post_date'
  5386. * and 'post_date_gmt' keys' values.
  5387. *
  5388. * By default, the comments will use the default settings for whether the
  5389. * comments are allowed. You can close them manually or keep them open by
  5390. * setting the value for the 'comment_status' key.
  5391. *
  5392. * @since 2.0.0
  5393. * @since 4.7.0 Added the `$wp_error` parameter to allow a WP_Error to be returned on failure.
  5394. * @since 5.6.0 Added the `$fire_after_hooks` parameter.
  5395. *
  5396. * @see wp_insert_post()
  5397. *
  5398. * @param string|array $args Arguments for inserting an attachment.
  5399. * @param string|false $file Optional. Filename.
  5400. * @param int $parent Optional. Parent post ID.
  5401. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  5402. * @param bool $fire_after_hooks Optional. Whether to fire the after insert hooks. Default true.
  5403. * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
  5404. */
  5405. function wp_insert_attachment( $args, $file = false, $parent = 0, $wp_error = false, $fire_after_hooks = true ) {
  5406. $defaults = array(
  5407. 'file' => $file,
  5408. 'post_parent' => 0,
  5409. );
  5410. $data = wp_parse_args( $args, $defaults );
  5411. if ( ! empty( $parent ) ) {
  5412. $data['post_parent'] = $parent;
  5413. }
  5414. $data['post_type'] = 'attachment';
  5415. return wp_insert_post( $data, $wp_error, $fire_after_hooks );
  5416. }
  5417. /**
  5418. * Trash or delete an attachment.
  5419. *
  5420. * When an attachment is permanently deleted, the file will also be removed.
  5421. * Deletion removes all post meta fields, taxonomy, comments, etc. associated
  5422. * with the attachment (except the main post).
  5423. *
  5424. * The attachment is moved to the Trash instead of permanently deleted unless Trash
  5425. * for media is disabled, item is already in the Trash, or $force_delete is true.
  5426. *
  5427. * @since 2.0.0
  5428. *
  5429. * @global wpdb $wpdb WordPress database abstraction object.
  5430. *
  5431. * @param int $post_id Attachment ID.
  5432. * @param bool $force_delete Optional. Whether to bypass Trash and force deletion.
  5433. * Default false.
  5434. * @return WP_Post|false|null Post data on success, false or null on failure.
  5435. */
  5436. function wp_delete_attachment( $post_id, $force_delete = false ) {
  5437. global $wpdb;
  5438. $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id ) );
  5439. if ( ! $post ) {
  5440. return $post;
  5441. }
  5442. $post = get_post( $post );
  5443. if ( 'attachment' !== $post->post_type ) {
  5444. return false;
  5445. }
  5446. if ( ! $force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' !== $post->post_status ) {
  5447. return wp_trash_post( $post_id );
  5448. }
  5449. /**
  5450. * Filters whether an attachment deletion should take place.
  5451. *
  5452. * @since 5.5.0
  5453. *
  5454. * @param bool|null $delete Whether to go forward with deletion.
  5455. * @param WP_Post $post Post object.
  5456. * @param bool $force_delete Whether to bypass the Trash.
  5457. */
  5458. $check = apply_filters( 'pre_delete_attachment', null, $post, $force_delete );
  5459. if ( null !== $check ) {
  5460. return $check;
  5461. }
  5462. delete_post_meta( $post_id, '_wp_trash_meta_status' );
  5463. delete_post_meta( $post_id, '_wp_trash_meta_time' );
  5464. $meta = wp_get_attachment_metadata( $post_id );
  5465. $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
  5466. $file = get_attached_file( $post_id );
  5467. if ( is_multisite() ) {
  5468. clean_dirsize_cache( $file );
  5469. }
  5470. /**
  5471. * Fires before an attachment is deleted, at the start of wp_delete_attachment().
  5472. *
  5473. * @since 2.0.0
  5474. * @since 5.5.0 Added the `$post` parameter.
  5475. *
  5476. * @param int $post_id Attachment ID.
  5477. * @param WP_Post $post Post object.
  5478. */
  5479. do_action( 'delete_attachment', $post_id, $post );
  5480. wp_delete_object_term_relationships( $post_id, array( 'category', 'post_tag' ) );
  5481. wp_delete_object_term_relationships( $post_id, get_object_taxonomies( $post->post_type ) );
  5482. // Delete all for any posts.
  5483. delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
  5484. wp_defer_comment_counting( true );
  5485. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ) );
  5486. foreach ( $comment_ids as $comment_id ) {
  5487. wp_delete_comment( $comment_id, true );
  5488. }
  5489. wp_defer_comment_counting( false );
  5490. $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ) );
  5491. foreach ( $post_meta_ids as $mid ) {
  5492. delete_metadata_by_mid( 'post', $mid );
  5493. }
  5494. /** This action is documented in wp-includes/post.php */
  5495. do_action( 'delete_post', $post_id, $post );
  5496. $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
  5497. if ( ! $result ) {
  5498. return false;
  5499. }
  5500. /** This action is documented in wp-includes/post.php */
  5501. do_action( 'deleted_post', $post_id, $post );
  5502. wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file );
  5503. clean_post_cache( $post );
  5504. return $post;
  5505. }
  5506. /**
  5507. * Deletes all files that belong to the given attachment.
  5508. *
  5509. * @since 4.9.7
  5510. *
  5511. * @global wpdb $wpdb WordPress database abstraction object.
  5512. *
  5513. * @param int $post_id Attachment ID.
  5514. * @param array $meta The attachment's meta data.
  5515. * @param array $backup_sizes The meta data for the attachment's backup images.
  5516. * @param string $file Absolute path to the attachment's file.
  5517. * @return bool True on success, false on failure.
  5518. */
  5519. function wp_delete_attachment_files( $post_id, $meta, $backup_sizes, $file ) {
  5520. global $wpdb;
  5521. $uploadpath = wp_get_upload_dir();
  5522. $deleted = true;
  5523. if ( ! empty( $meta['thumb'] ) ) {
  5524. // Don't delete the thumb if another attachment uses it.
  5525. if ( ! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', $post_id ) ) ) {
  5526. $thumbfile = str_replace( wp_basename( $file ), $meta['thumb'], $file );
  5527. if ( ! empty( $thumbfile ) ) {
  5528. $thumbfile = path_join( $uploadpath['basedir'], $thumbfile );
  5529. $thumbdir = path_join( $uploadpath['basedir'], dirname( $file ) );
  5530. if ( ! wp_delete_file_from_directory( $thumbfile, $thumbdir ) ) {
  5531. $deleted = false;
  5532. }
  5533. }
  5534. }
  5535. }
  5536. // Remove intermediate and backup images if there are any.
  5537. if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
  5538. $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
  5539. foreach ( $meta['sizes'] as $size => $sizeinfo ) {
  5540. $intermediate_file = str_replace( wp_basename( $file ), $sizeinfo['file'], $file );
  5541. if ( ! empty( $intermediate_file ) ) {
  5542. $intermediate_file = path_join( $uploadpath['basedir'], $intermediate_file );
  5543. if ( ! wp_delete_file_from_directory( $intermediate_file, $intermediate_dir ) ) {
  5544. $deleted = false;
  5545. }
  5546. }
  5547. }
  5548. }
  5549. if ( ! empty( $meta['original_image'] ) ) {
  5550. if ( empty( $intermediate_dir ) ) {
  5551. $intermediate_dir = path_join( $uploadpath['basedir'], dirname( $file ) );
  5552. }
  5553. $original_image = str_replace( wp_basename( $file ), $meta['original_image'], $file );
  5554. if ( ! empty( $original_image ) ) {
  5555. $original_image = path_join( $uploadpath['basedir'], $original_image );
  5556. if ( ! wp_delete_file_from_directory( $original_image, $intermediate_dir ) ) {
  5557. $deleted = false;
  5558. }
  5559. }
  5560. }
  5561. if ( is_array( $backup_sizes ) ) {
  5562. $del_dir = path_join( $uploadpath['basedir'], dirname( $meta['file'] ) );
  5563. foreach ( $backup_sizes as $size ) {
  5564. $del_file = path_join( dirname( $meta['file'] ), $size['file'] );
  5565. if ( ! empty( $del_file ) ) {
  5566. $del_file = path_join( $uploadpath['basedir'], $del_file );
  5567. if ( ! wp_delete_file_from_directory( $del_file, $del_dir ) ) {
  5568. $deleted = false;
  5569. }
  5570. }
  5571. }
  5572. }
  5573. if ( ! wp_delete_file_from_directory( $file, $uploadpath['basedir'] ) ) {
  5574. $deleted = false;
  5575. }
  5576. return $deleted;
  5577. }
  5578. /**
  5579. * Retrieves attachment metadata for attachment ID.
  5580. *
  5581. * @since 2.1.0
  5582. *
  5583. * @param int $attachment_id Attachment post ID. Defaults to global $post.
  5584. * @param bool $unfiltered Optional. If true, filters are not run. Default false.
  5585. * @return array|false {
  5586. * Attachment metadata. False on failure.
  5587. *
  5588. * @type int $width The width of the attachment.
  5589. * @type int $height The height of the attachment.
  5590. * @type string $file The file path relative to `wp-content/uploads`.
  5591. * @type array $sizes Keys are size slugs, each value is an array containing
  5592. * 'file', 'width', 'height', and 'mime-type'.
  5593. * @type array $image_meta Image metadata.
  5594. * }
  5595. */
  5596. function wp_get_attachment_metadata( $attachment_id = 0, $unfiltered = false ) {
  5597. $attachment_id = (int) $attachment_id;
  5598. if ( ! $attachment_id ) {
  5599. $post = get_post();
  5600. if ( ! $post ) {
  5601. return false;
  5602. }
  5603. $attachment_id = $post->ID;
  5604. }
  5605. $data = get_post_meta( $attachment_id, '_wp_attachment_metadata', true );
  5606. if ( ! $data ) {
  5607. return false;
  5608. }
  5609. if ( $unfiltered ) {
  5610. return $data;
  5611. }
  5612. /**
  5613. * Filters the attachment meta data.
  5614. *
  5615. * @since 2.1.0
  5616. *
  5617. * @param array $data Array of meta data for the given attachment.
  5618. * @param int $attachment_id Attachment post ID.
  5619. */
  5620. return apply_filters( 'wp_get_attachment_metadata', $data, $attachment_id );
  5621. }
  5622. /**
  5623. * Updates metadata for an attachment.
  5624. *
  5625. * @since 2.1.0
  5626. *
  5627. * @param int $attachment_id Attachment post ID.
  5628. * @param array $data Attachment meta data.
  5629. * @return int|false False if $post is invalid.
  5630. */
  5631. function wp_update_attachment_metadata( $attachment_id, $data ) {
  5632. $attachment_id = (int) $attachment_id;
  5633. $post = get_post( $attachment_id );
  5634. if ( ! $post ) {
  5635. return false;
  5636. }
  5637. /**
  5638. * Filters the updated attachment meta data.
  5639. *
  5640. * @since 2.1.0
  5641. *
  5642. * @param array $data Array of updated attachment meta data.
  5643. * @param int $attachment_id Attachment post ID.
  5644. */
  5645. $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
  5646. if ( $data ) {
  5647. return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
  5648. } else {
  5649. return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
  5650. }
  5651. }
  5652. /**
  5653. * Retrieve the URL for an attachment.
  5654. *
  5655. * @since 2.1.0
  5656. *
  5657. * @global string $pagenow
  5658. *
  5659. * @param int $attachment_id Optional. Attachment post ID. Defaults to global $post.
  5660. * @return string|false Attachment URL, otherwise false.
  5661. */
  5662. function wp_get_attachment_url( $attachment_id = 0 ) {
  5663. global $pagenow;
  5664. $attachment_id = (int) $attachment_id;
  5665. $post = get_post( $attachment_id );
  5666. if ( ! $post ) {
  5667. return false;
  5668. }
  5669. if ( 'attachment' !== $post->post_type ) {
  5670. return false;
  5671. }
  5672. $url = '';
  5673. // Get attached file.
  5674. $file = get_post_meta( $post->ID, '_wp_attached_file', true );
  5675. if ( $file ) {
  5676. // Get upload directory.
  5677. $uploads = wp_get_upload_dir();
  5678. if ( $uploads && false === $uploads['error'] ) {
  5679. // Check that the upload base exists in the file location.
  5680. if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
  5681. // Replace file location with url location.
  5682. $url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
  5683. } elseif ( false !== strpos( $file, 'wp-content/uploads' ) ) {
  5684. // Get the directory name relative to the basedir (back compat for pre-2.7 uploads).
  5685. $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . wp_basename( $file );
  5686. } else {
  5687. // It's a newly-uploaded file, therefore $file is relative to the basedir.
  5688. $url = $uploads['baseurl'] . "/$file";
  5689. }
  5690. }
  5691. }
  5692. /*
  5693. * If any of the above options failed, Fallback on the GUID as used pre-2.7,
  5694. * not recommended to rely upon this.
  5695. */
  5696. if ( ! $url ) {
  5697. $url = get_the_guid( $post->ID );
  5698. }
  5699. // On SSL front end, URLs should be HTTPS.
  5700. if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $pagenow ) {
  5701. $url = set_url_scheme( $url );
  5702. }
  5703. /**
  5704. * Filters the attachment URL.
  5705. *
  5706. * @since 2.1.0
  5707. *
  5708. * @param string $url URL for the given attachment.
  5709. * @param int $attachment_id Attachment post ID.
  5710. */
  5711. $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
  5712. if ( ! $url ) {
  5713. return false;
  5714. }
  5715. return $url;
  5716. }
  5717. /**
  5718. * Retrieves the caption for an attachment.
  5719. *
  5720. * @since 4.6.0
  5721. *
  5722. * @param int $post_id Optional. Attachment ID. Default is the ID of the global `$post`.
  5723. * @return string|false Attachment caption on success, false on failure.
  5724. */
  5725. function wp_get_attachment_caption( $post_id = 0 ) {
  5726. $post_id = (int) $post_id;
  5727. $post = get_post( $post_id );
  5728. if ( ! $post ) {
  5729. return false;
  5730. }
  5731. if ( 'attachment' !== $post->post_type ) {
  5732. return false;
  5733. }
  5734. $caption = $post->post_excerpt;
  5735. /**
  5736. * Filters the attachment caption.
  5737. *
  5738. * @since 4.6.0
  5739. *
  5740. * @param string $caption Caption for the given attachment.
  5741. * @param int $post_id Attachment ID.
  5742. */
  5743. return apply_filters( 'wp_get_attachment_caption', $caption, $post->ID );
  5744. }
  5745. /**
  5746. * Retrieve thumbnail for an attachment.
  5747. *
  5748. * @since 2.1.0
  5749. *
  5750. * @param int $post_id Optional. Attachment ID. Default 0.
  5751. * @return string|false Thumbnail file path on success, false on failure.
  5752. */
  5753. function wp_get_attachment_thumb_file( $post_id = 0 ) {
  5754. $post_id = (int) $post_id;
  5755. $post = get_post( $post_id );
  5756. if ( ! $post ) {
  5757. return false;
  5758. }
  5759. $imagedata = wp_get_attachment_metadata( $post->ID );
  5760. if ( ! is_array( $imagedata ) ) {
  5761. return false;
  5762. }
  5763. $file = get_attached_file( $post->ID );
  5764. if ( ! empty( $imagedata['thumb'] ) ) {
  5765. $thumbfile = str_replace( wp_basename( $file ), $imagedata['thumb'], $file );
  5766. if ( file_exists( $thumbfile ) ) {
  5767. /**
  5768. * Filters the attachment thumbnail file path.
  5769. *
  5770. * @since 2.1.0
  5771. *
  5772. * @param string $thumbfile File path to the attachment thumbnail.
  5773. * @param int $post_id Attachment ID.
  5774. */
  5775. return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
  5776. }
  5777. }
  5778. return false;
  5779. }
  5780. /**
  5781. * Retrieve URL for an attachment thumbnail.
  5782. *
  5783. * @since 2.1.0
  5784. *
  5785. * @param int $post_id Optional. Attachment ID. Default 0.
  5786. * @return string|false Thumbnail URL on success, false on failure.
  5787. */
  5788. function wp_get_attachment_thumb_url( $post_id = 0 ) {
  5789. $post_id = (int) $post_id;
  5790. $post = get_post( $post_id );
  5791. if ( ! $post ) {
  5792. return false;
  5793. }
  5794. $url = wp_get_attachment_url( $post->ID );
  5795. if ( ! $url ) {
  5796. return false;
  5797. }
  5798. $sized = image_downsize( $post_id, 'thumbnail' );
  5799. if ( $sized ) {
  5800. return $sized[0];
  5801. }
  5802. $thumb = wp_get_attachment_thumb_file( $post->ID );
  5803. if ( ! $thumb ) {
  5804. return false;
  5805. }
  5806. $url = str_replace( wp_basename( $url ), wp_basename( $thumb ), $url );
  5807. /**
  5808. * Filters the attachment thumbnail URL.
  5809. *
  5810. * @since 2.1.0
  5811. *
  5812. * @param string $url URL for the attachment thumbnail.
  5813. * @param int $post_id Attachment ID.
  5814. */
  5815. return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
  5816. }
  5817. /**
  5818. * Verifies an attachment is of a given type.
  5819. *
  5820. * @since 4.2.0
  5821. *
  5822. * @param string $type Attachment type. Accepts 'image', 'audio', or 'video'.
  5823. * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
  5824. * @return bool True if one of the accepted types, false otherwise.
  5825. */
  5826. function wp_attachment_is( $type, $post = null ) {
  5827. $post = get_post( $post );
  5828. if ( ! $post ) {
  5829. return false;
  5830. }
  5831. $file = get_attached_file( $post->ID );
  5832. if ( ! $file ) {
  5833. return false;
  5834. }
  5835. if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
  5836. return true;
  5837. }
  5838. $check = wp_check_filetype( $file );
  5839. if ( empty( $check['ext'] ) ) {
  5840. return false;
  5841. }
  5842. $ext = $check['ext'];
  5843. if ( 'import' !== $post->post_mime_type ) {
  5844. return $type === $ext;
  5845. }
  5846. switch ( $type ) {
  5847. case 'image':
  5848. $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'webp' );
  5849. return in_array( $ext, $image_exts, true );
  5850. case 'audio':
  5851. return in_array( $ext, wp_get_audio_extensions(), true );
  5852. case 'video':
  5853. return in_array( $ext, wp_get_video_extensions(), true );
  5854. default:
  5855. return $type === $ext;
  5856. }
  5857. }
  5858. /**
  5859. * Determines whether an attachment is an image.
  5860. *
  5861. * For more information on this and similar theme functions, check out
  5862. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  5863. * Conditional Tags} article in the Theme Developer Handbook.
  5864. *
  5865. * @since 2.1.0
  5866. * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
  5867. * allowed WP_Post object to be passed.
  5868. *
  5869. * @param int|WP_Post $post Optional. Attachment ID or object. Default is global $post.
  5870. * @return bool Whether the attachment is an image.
  5871. */
  5872. function wp_attachment_is_image( $post = null ) {
  5873. return wp_attachment_is( 'image', $post );
  5874. }
  5875. /**
  5876. * Retrieve the icon for a MIME type or attachment.
  5877. *
  5878. * @since 2.1.0
  5879. *
  5880. * @param string|int $mime MIME type or attachment ID.
  5881. * @return string|false Icon, false otherwise.
  5882. */
  5883. function wp_mime_type_icon( $mime = 0 ) {
  5884. if ( ! is_numeric( $mime ) ) {
  5885. $icon = wp_cache_get( "mime_type_icon_$mime" );
  5886. }
  5887. $post_id = 0;
  5888. if ( empty( $icon ) ) {
  5889. $post_mimes = array();
  5890. if ( is_numeric( $mime ) ) {
  5891. $mime = (int) $mime;
  5892. $post = get_post( $mime );
  5893. if ( $post ) {
  5894. $post_id = (int) $post->ID;
  5895. $file = get_attached_file( $post_id );
  5896. $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $file );
  5897. if ( ! empty( $ext ) ) {
  5898. $post_mimes[] = $ext;
  5899. $ext_type = wp_ext2type( $ext );
  5900. if ( $ext_type ) {
  5901. $post_mimes[] = $ext_type;
  5902. }
  5903. }
  5904. $mime = $post->post_mime_type;
  5905. } else {
  5906. $mime = 0;
  5907. }
  5908. } else {
  5909. $post_mimes[] = $mime;
  5910. }
  5911. $icon_files = wp_cache_get( 'icon_files' );
  5912. if ( ! is_array( $icon_files ) ) {
  5913. /**
  5914. * Filters the icon directory path.
  5915. *
  5916. * @since 2.0.0
  5917. *
  5918. * @param string $path Icon directory absolute path.
  5919. */
  5920. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  5921. /**
  5922. * Filters the icon directory URI.
  5923. *
  5924. * @since 2.0.0
  5925. *
  5926. * @param string $uri Icon directory URI.
  5927. */
  5928. $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
  5929. /**
  5930. * Filters the array of icon directory URIs.
  5931. *
  5932. * @since 2.5.0
  5933. *
  5934. * @param string[] $uris Array of icon directory URIs keyed by directory absolute path.
  5935. */
  5936. $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
  5937. $icon_files = array();
  5938. while ( $dirs ) {
  5939. $keys = array_keys( $dirs );
  5940. $dir = array_shift( $keys );
  5941. $uri = array_shift( $dirs );
  5942. $dh = opendir( $dir );
  5943. if ( $dh ) {
  5944. while ( false !== $file = readdir( $dh ) ) {
  5945. $file = wp_basename( $file );
  5946. if ( '.' === substr( $file, 0, 1 ) ) {
  5947. continue;
  5948. }
  5949. $ext = strtolower( substr( $file, -4 ) );
  5950. if ( ! in_array( $ext, array( '.png', '.gif', '.jpg' ), true ) ) {
  5951. if ( is_dir( "$dir/$file" ) ) {
  5952. $dirs[ "$dir/$file" ] = "$uri/$file";
  5953. }
  5954. continue;
  5955. }
  5956. $icon_files[ "$dir/$file" ] = "$uri/$file";
  5957. }
  5958. closedir( $dh );
  5959. }
  5960. }
  5961. wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
  5962. }
  5963. $types = array();
  5964. // Icon wp_basename - extension = MIME wildcard.
  5965. foreach ( $icon_files as $file => $uri ) {
  5966. $types[ preg_replace( '/^([^.]*).*$/', '$1', wp_basename( $file ) ) ] =& $icon_files[ $file ];
  5967. }
  5968. if ( ! empty( $mime ) ) {
  5969. $post_mimes[] = substr( $mime, 0, strpos( $mime, '/' ) );
  5970. $post_mimes[] = substr( $mime, strpos( $mime, '/' ) + 1 );
  5971. $post_mimes[] = str_replace( '/', '_', $mime );
  5972. }
  5973. $matches = wp_match_mime_types( array_keys( $types ), $post_mimes );
  5974. $matches['default'] = array( 'default' );
  5975. foreach ( $matches as $match => $wilds ) {
  5976. foreach ( $wilds as $wild ) {
  5977. if ( ! isset( $types[ $wild ] ) ) {
  5978. continue;
  5979. }
  5980. $icon = $types[ $wild ];
  5981. if ( ! is_numeric( $mime ) ) {
  5982. wp_cache_add( "mime_type_icon_$mime", $icon );
  5983. }
  5984. break 2;
  5985. }
  5986. }
  5987. }
  5988. /**
  5989. * Filters the mime type icon.
  5990. *
  5991. * @since 2.1.0
  5992. *
  5993. * @param string $icon Path to the mime type icon.
  5994. * @param string $mime Mime type.
  5995. * @param int $post_id Attachment ID. Will equal 0 if the function passed
  5996. * the mime type.
  5997. */
  5998. return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
  5999. }
  6000. /**
  6001. * Check for changed slugs for published post objects and save the old slug.
  6002. *
  6003. * The function is used when a post object of any type is updated,
  6004. * by comparing the current and previous post objects.
  6005. *
  6006. * If the slug was changed and not already part of the old slugs then it will be
  6007. * added to the post meta field ('_wp_old_slug') for storing old slugs for that
  6008. * post.
  6009. *
  6010. * The most logically usage of this function is redirecting changed post objects, so
  6011. * that those that linked to an changed post will be redirected to the new post.
  6012. *
  6013. * @since 2.1.0
  6014. *
  6015. * @param int $post_id Post ID.
  6016. * @param WP_Post $post The Post Object
  6017. * @param WP_Post $post_before The Previous Post Object
  6018. */
  6019. function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
  6020. // Don't bother if it hasn't changed.
  6021. if ( $post->post_name == $post_before->post_name ) {
  6022. return;
  6023. }
  6024. // We're only concerned with published, non-hierarchical objects.
  6025. if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
  6026. return;
  6027. }
  6028. $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
  6029. // If we haven't added this old slug before, add it now.
  6030. if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs, true ) ) {
  6031. add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
  6032. }
  6033. // If the new slug was used previously, delete it from the list.
  6034. if ( in_array( $post->post_name, $old_slugs, true ) ) {
  6035. delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
  6036. }
  6037. }
  6038. /**
  6039. * Check for changed dates for published post objects and save the old date.
  6040. *
  6041. * The function is used when a post object of any type is updated,
  6042. * by comparing the current and previous post objects.
  6043. *
  6044. * If the date was changed and not already part of the old dates then it will be
  6045. * added to the post meta field ('_wp_old_date') for storing old dates for that
  6046. * post.
  6047. *
  6048. * The most logically usage of this function is redirecting changed post objects, so
  6049. * that those that linked to an changed post will be redirected to the new post.
  6050. *
  6051. * @since 4.9.3
  6052. *
  6053. * @param int $post_id Post ID.
  6054. * @param WP_Post $post The Post Object
  6055. * @param WP_Post $post_before The Previous Post Object
  6056. */
  6057. function wp_check_for_changed_dates( $post_id, $post, $post_before ) {
  6058. $previous_date = gmdate( 'Y-m-d', strtotime( $post_before->post_date ) );
  6059. $new_date = gmdate( 'Y-m-d', strtotime( $post->post_date ) );
  6060. // Don't bother if it hasn't changed.
  6061. if ( $new_date == $previous_date ) {
  6062. return;
  6063. }
  6064. // We're only concerned with published, non-hierarchical objects.
  6065. if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
  6066. return;
  6067. }
  6068. $old_dates = (array) get_post_meta( $post_id, '_wp_old_date' );
  6069. // If we haven't added this old date before, add it now.
  6070. if ( ! empty( $previous_date ) && ! in_array( $previous_date, $old_dates, true ) ) {
  6071. add_post_meta( $post_id, '_wp_old_date', $previous_date );
  6072. }
  6073. // If the new slug was used previously, delete it from the list.
  6074. if ( in_array( $new_date, $old_dates, true ) ) {
  6075. delete_post_meta( $post_id, '_wp_old_date', $new_date );
  6076. }
  6077. }
  6078. /**
  6079. * Retrieve the private post SQL based on capability.
  6080. *
  6081. * This function provides a standardized way to appropriately select on the
  6082. * post_status of a post type. The function will return a piece of SQL code
  6083. * that can be added to a WHERE clause; this SQL is constructed to allow all
  6084. * published posts, and all private posts to which the user has access.
  6085. *
  6086. * @since 2.2.0
  6087. * @since 4.3.0 Added the ability to pass an array to `$post_type`.
  6088. *
  6089. * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
  6090. * @return string SQL code that can be added to a where clause.
  6091. */
  6092. function get_private_posts_cap_sql( $post_type ) {
  6093. return get_posts_by_author_sql( $post_type, false );
  6094. }
  6095. /**
  6096. * Retrieve the post SQL based on capability, author, and type.
  6097. *
  6098. * @since 3.0.0
  6099. * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
  6100. *
  6101. * @see get_private_posts_cap_sql()
  6102. * @global wpdb $wpdb WordPress database abstraction object.
  6103. *
  6104. * @param string|string[] $post_type Single post type or an array of post types.
  6105. * @param bool $full Optional. Returns a full WHERE statement instead of just
  6106. * an 'andalso' term. Default true.
  6107. * @param int $post_author Optional. Query posts having a single author ID. Default null.
  6108. * @param bool $public_only Optional. Only return public posts. Skips cap checks for
  6109. * $current_user. Default false.
  6110. * @return string SQL WHERE code that can be added to a query.
  6111. */
  6112. function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
  6113. global $wpdb;
  6114. if ( is_array( $post_type ) ) {
  6115. $post_types = $post_type;
  6116. } else {
  6117. $post_types = array( $post_type );
  6118. }
  6119. $post_type_clauses = array();
  6120. foreach ( $post_types as $post_type ) {
  6121. $post_type_obj = get_post_type_object( $post_type );
  6122. if ( ! $post_type_obj ) {
  6123. continue;
  6124. }
  6125. /**
  6126. * Filters the capability to read private posts for a custom post type
  6127. * when generating SQL for getting posts by author.
  6128. *
  6129. * @since 2.2.0
  6130. * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
  6131. *
  6132. * @param string $cap Capability.
  6133. */
  6134. $cap = apply_filters_deprecated( 'pub_priv_sql_capability', array( '' ), '3.2.0' );
  6135. if ( ! $cap ) {
  6136. $cap = current_user_can( $post_type_obj->cap->read_private_posts );
  6137. }
  6138. // Only need to check the cap if $public_only is false.
  6139. $post_status_sql = "post_status = 'publish'";
  6140. if ( false === $public_only ) {
  6141. if ( $cap ) {
  6142. // Does the user have the capability to view private posts? Guess so.
  6143. $post_status_sql .= " OR post_status = 'private'";
  6144. } elseif ( is_user_logged_in() ) {
  6145. // Users can view their own private posts.
  6146. $id = get_current_user_id();
  6147. if ( null === $post_author || ! $full ) {
  6148. $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
  6149. } elseif ( $id == (int) $post_author ) {
  6150. $post_status_sql .= " OR post_status = 'private'";
  6151. } // Else none.
  6152. } // Else none.
  6153. }
  6154. $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
  6155. }
  6156. if ( empty( $post_type_clauses ) ) {
  6157. return $full ? 'WHERE 1 = 0' : '1 = 0';
  6158. }
  6159. $sql = '( ' . implode( ' OR ', $post_type_clauses ) . ' )';
  6160. if ( null !== $post_author ) {
  6161. $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
  6162. }
  6163. if ( $full ) {
  6164. $sql = 'WHERE ' . $sql;
  6165. }
  6166. return $sql;
  6167. }
  6168. /**
  6169. * Retrieves the most recent time that a post on the site was published.
  6170. *
  6171. * The server timezone is the default and is the difference between GMT and
  6172. * server time. The 'blog' value is the date when the last post was posted.
  6173. * The 'gmt' is when the last post was posted in GMT formatted date.
  6174. *
  6175. * @since 0.71
  6176. * @since 4.4.0 The `$post_type` argument was added.
  6177. *
  6178. * @param string $timezone Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
  6179. * 'server' uses the server's internal timezone.
  6180. * 'blog' uses the `post_date` field, which proxies to the timezone set for the site.
  6181. * 'gmt' uses the `post_date_gmt` field.
  6182. * Default 'server'.
  6183. * @param string $post_type Optional. The post type to check. Default 'any'.
  6184. * @return string The date of the last post, or false on failure.
  6185. */
  6186. function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
  6187. $lastpostdate = _get_last_post_time( $timezone, 'date', $post_type );
  6188. /**
  6189. * Filters the most recent time that a post on the site was published.
  6190. *
  6191. * @since 2.3.0
  6192. * @since 5.5.0 Added the `$post_type` parameter.
  6193. *
  6194. * @param string|false $lastpostdate The most recent time that a post was published,
  6195. * in 'Y-m-d H:i:s' format. False on failure.
  6196. * @param string $timezone Location to use for getting the post published date.
  6197. * See get_lastpostdate() for accepted `$timezone` values.
  6198. * @param string $post_type The post type to check.
  6199. */
  6200. return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone, $post_type );
  6201. }
  6202. /**
  6203. * Get the most recent time that a post on the site was modified.
  6204. *
  6205. * The server timezone is the default and is the difference between GMT and
  6206. * server time. The 'blog' value is just when the last post was modified.
  6207. * The 'gmt' is when the last post was modified in GMT time.
  6208. *
  6209. * @since 1.2.0
  6210. * @since 4.4.0 The `$post_type` argument was added.
  6211. *
  6212. * @param string $timezone Optional. The timezone for the timestamp. See get_lastpostdate()
  6213. * for information on accepted values.
  6214. * Default 'server'.
  6215. * @param string $post_type Optional. The post type to check. Default 'any'.
  6216. * @return string The timestamp in 'Y-m-d H:i:s' format, or false on failure.
  6217. */
  6218. function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
  6219. /**
  6220. * Pre-filter the return value of get_lastpostmodified() before the query is run.
  6221. *
  6222. * @since 4.4.0
  6223. *
  6224. * @param string|false $lastpostmodified The most recent time that a post was modified,
  6225. * in 'Y-m-d H:i:s' format, or false. Returning anything
  6226. * other than false will short-circuit the function.
  6227. * @param string $timezone Location to use for getting the post modified date.
  6228. * See get_lastpostdate() for accepted `$timezone` values.
  6229. * @param string $post_type The post type to check.
  6230. */
  6231. $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
  6232. if ( false !== $lastpostmodified ) {
  6233. return $lastpostmodified;
  6234. }
  6235. $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
  6236. $lastpostdate = get_lastpostdate( $timezone, $post_type );
  6237. if ( $lastpostdate > $lastpostmodified ) {
  6238. $lastpostmodified = $lastpostdate;
  6239. }
  6240. /**
  6241. * Filters the most recent time that a post on the site was modified.
  6242. *
  6243. * @since 2.3.0
  6244. * @since 5.5.0 Added the `$post_type` parameter.
  6245. *
  6246. * @param string|false $lastpostmodified The most recent time that a post was modified,
  6247. * in 'Y-m-d H:i:s' format. False on failure.
  6248. * @param string $timezone Location to use for getting the post modified date.
  6249. * See get_lastpostdate() for accepted `$timezone` values.
  6250. * @param string $post_type The post type to check.
  6251. */
  6252. return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone, $post_type );
  6253. }
  6254. /**
  6255. * Gets the timestamp of the last time any post was modified or published.
  6256. *
  6257. * @since 3.1.0
  6258. * @since 4.4.0 The `$post_type` argument was added.
  6259. * @access private
  6260. *
  6261. * @global wpdb $wpdb WordPress database abstraction object.
  6262. *
  6263. * @param string $timezone The timezone for the timestamp. See get_lastpostdate().
  6264. * for information on accepted values.
  6265. * @param string $field Post field to check. Accepts 'date' or 'modified'.
  6266. * @param string $post_type Optional. The post type to check. Default 'any'.
  6267. * @return string|false The timestamp in 'Y-m-d H:i:s' format, or false on failure.
  6268. */
  6269. function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
  6270. global $wpdb;
  6271. if ( ! in_array( $field, array( 'date', 'modified' ), true ) ) {
  6272. return false;
  6273. }
  6274. $timezone = strtolower( $timezone );
  6275. $key = "lastpost{$field}:$timezone";
  6276. if ( 'any' !== $post_type ) {
  6277. $key .= ':' . sanitize_key( $post_type );
  6278. }
  6279. $date = wp_cache_get( $key, 'timeinfo' );
  6280. if ( false !== $date ) {
  6281. return $date;
  6282. }
  6283. if ( 'any' === $post_type ) {
  6284. $post_types = get_post_types( array( 'public' => true ) );
  6285. array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
  6286. $post_types = "'" . implode( "', '", $post_types ) . "'";
  6287. } else {
  6288. $post_types = "'" . sanitize_key( $post_type ) . "'";
  6289. }
  6290. switch ( $timezone ) {
  6291. case 'gmt':
  6292. $date = $wpdb->get_var( "SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
  6293. break;
  6294. case 'blog':
  6295. $date = $wpdb->get_var( "SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
  6296. break;
  6297. case 'server':
  6298. $add_seconds_server = gmdate( 'Z' );
  6299. $date = $wpdb->get_var( "SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
  6300. break;
  6301. }
  6302. if ( $date ) {
  6303. wp_cache_set( $key, $date, 'timeinfo' );
  6304. return $date;
  6305. }
  6306. return false;
  6307. }
  6308. /**
  6309. * Updates posts in cache.
  6310. *
  6311. * @since 1.5.1
  6312. *
  6313. * @param WP_Post[] $posts Array of post objects (passed by reference).
  6314. */
  6315. function update_post_cache( &$posts ) {
  6316. if ( ! $posts ) {
  6317. return;
  6318. }
  6319. foreach ( $posts as $post ) {
  6320. wp_cache_add( $post->ID, $post, 'posts' );
  6321. }
  6322. }
  6323. /**
  6324. * Will clean the post in the cache.
  6325. *
  6326. * Cleaning means delete from the cache of the post. Will call to clean the term
  6327. * object cache associated with the post ID.
  6328. *
  6329. * This function not run if $_wp_suspend_cache_invalidation is not empty. See
  6330. * wp_suspend_cache_invalidation().
  6331. *
  6332. * @since 2.0.0
  6333. *
  6334. * @global bool $_wp_suspend_cache_invalidation
  6335. *
  6336. * @param int|WP_Post $post Post ID or post object to remove from the cache.
  6337. */
  6338. function clean_post_cache( $post ) {
  6339. global $_wp_suspend_cache_invalidation;
  6340. if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
  6341. return;
  6342. }
  6343. $post = get_post( $post );
  6344. if ( ! $post ) {
  6345. return;
  6346. }
  6347. wp_cache_delete( $post->ID, 'posts' );
  6348. wp_cache_delete( $post->ID, 'post_meta' );
  6349. clean_object_term_cache( $post->ID, $post->post_type );
  6350. wp_cache_delete( 'wp_get_archives', 'general' );
  6351. /**
  6352. * Fires immediately after the given post's cache is cleaned.
  6353. *
  6354. * @since 2.5.0
  6355. *
  6356. * @param int $post_id Post ID.
  6357. * @param WP_Post $post Post object.
  6358. */
  6359. do_action( 'clean_post_cache', $post->ID, $post );
  6360. if ( 'page' === $post->post_type ) {
  6361. wp_cache_delete( 'all_page_ids', 'posts' );
  6362. /**
  6363. * Fires immediately after the given page's cache is cleaned.
  6364. *
  6365. * @since 2.5.0
  6366. *
  6367. * @param int $post_id Post ID.
  6368. */
  6369. do_action( 'clean_page_cache', $post->ID );
  6370. }
  6371. wp_cache_set( 'last_changed', microtime(), 'posts' );
  6372. }
  6373. /**
  6374. * Call major cache updating functions for list of Post objects.
  6375. *
  6376. * @since 1.5.0
  6377. *
  6378. * @param WP_Post[] $posts Array of Post objects
  6379. * @param string $post_type Optional. Post type. Default 'post'.
  6380. * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
  6381. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  6382. */
  6383. function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
  6384. // No point in doing all this work if we didn't match any posts.
  6385. if ( ! $posts ) {
  6386. return;
  6387. }
  6388. update_post_cache( $posts );
  6389. $post_ids = array();
  6390. foreach ( $posts as $post ) {
  6391. $post_ids[] = $post->ID;
  6392. }
  6393. if ( ! $post_type ) {
  6394. $post_type = 'any';
  6395. }
  6396. if ( $update_term_cache ) {
  6397. if ( is_array( $post_type ) ) {
  6398. $ptypes = $post_type;
  6399. } elseif ( 'any' === $post_type ) {
  6400. $ptypes = array();
  6401. // Just use the post_types in the supplied posts.
  6402. foreach ( $posts as $post ) {
  6403. $ptypes[] = $post->post_type;
  6404. }
  6405. $ptypes = array_unique( $ptypes );
  6406. } else {
  6407. $ptypes = array( $post_type );
  6408. }
  6409. if ( ! empty( $ptypes ) ) {
  6410. update_object_term_cache( $post_ids, $ptypes );
  6411. }
  6412. }
  6413. if ( $update_meta_cache ) {
  6414. update_postmeta_cache( $post_ids );
  6415. }
  6416. }
  6417. /**
  6418. * Updates metadata cache for list of post IDs.
  6419. *
  6420. * Performs SQL query to retrieve the metadata for the post IDs and updates the
  6421. * metadata cache for the posts. Therefore, the functions, which call this
  6422. * function, do not need to perform SQL queries on their own.
  6423. *
  6424. * @since 2.1.0
  6425. *
  6426. * @param int[] $post_ids Array of post IDs.
  6427. * @return array|false An array of metadata on success, false if there is nothing to update.
  6428. */
  6429. function update_postmeta_cache( $post_ids ) {
  6430. return update_meta_cache( 'post', $post_ids );
  6431. }
  6432. /**
  6433. * Will clean the attachment in the cache.
  6434. *
  6435. * Cleaning means delete from the cache. Optionally will clean the term
  6436. * object cache associated with the attachment ID.
  6437. *
  6438. * This function will not run if $_wp_suspend_cache_invalidation is not empty.
  6439. *
  6440. * @since 3.0.0
  6441. *
  6442. * @global bool $_wp_suspend_cache_invalidation
  6443. *
  6444. * @param int $id The attachment ID in the cache to clean.
  6445. * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
  6446. */
  6447. function clean_attachment_cache( $id, $clean_terms = false ) {
  6448. global $_wp_suspend_cache_invalidation;
  6449. if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
  6450. return;
  6451. }
  6452. $id = (int) $id;
  6453. wp_cache_delete( $id, 'posts' );
  6454. wp_cache_delete( $id, 'post_meta' );
  6455. if ( $clean_terms ) {
  6456. clean_object_term_cache( $id, 'attachment' );
  6457. }
  6458. /**
  6459. * Fires after the given attachment's cache is cleaned.
  6460. *
  6461. * @since 3.0.0
  6462. *
  6463. * @param int $id Attachment ID.
  6464. */
  6465. do_action( 'clean_attachment_cache', $id );
  6466. }
  6467. //
  6468. // Hooks.
  6469. //
  6470. /**
  6471. * Hook for managing future post transitions to published.
  6472. *
  6473. * @since 2.3.0
  6474. * @access private
  6475. *
  6476. * @see wp_clear_scheduled_hook()
  6477. * @global wpdb $wpdb WordPress database abstraction object.
  6478. *
  6479. * @param string $new_status New post status.
  6480. * @param string $old_status Previous post status.
  6481. * @param WP_Post $post Post object.
  6482. */
  6483. function _transition_post_status( $new_status, $old_status, $post ) {
  6484. global $wpdb;
  6485. if ( 'publish' !== $old_status && 'publish' === $new_status ) {
  6486. // Reset GUID if transitioning to publish and it is empty.
  6487. if ( '' === get_the_guid( $post->ID ) ) {
  6488. $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
  6489. }
  6490. /**
  6491. * Fires when a post's status is transitioned from private to published.
  6492. *
  6493. * @since 1.5.0
  6494. * @deprecated 2.3.0 Use {@see 'private_to_publish'} instead.
  6495. *
  6496. * @param int $post_id Post ID.
  6497. */
  6498. do_action_deprecated( 'private_to_published', array( $post->ID ), '2.3.0', 'private_to_publish' );
  6499. }
  6500. // If published posts changed clear the lastpostmodified cache.
  6501. if ( 'publish' === $new_status || 'publish' === $old_status ) {
  6502. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  6503. wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
  6504. wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
  6505. wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
  6506. }
  6507. }
  6508. if ( $new_status !== $old_status ) {
  6509. wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
  6510. wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
  6511. }
  6512. // Always clears the hook in case the post status bounced from future to draft.
  6513. wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
  6514. }
  6515. /**
  6516. * Hook used to schedule publication for a post marked for the future.
  6517. *
  6518. * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
  6519. *
  6520. * @since 2.3.0
  6521. * @access private
  6522. *
  6523. * @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
  6524. * as deprecated with _deprecated_argument() as it conflicts with
  6525. * wp_transition_post_status() and the default filter for _future_post_hook().
  6526. * @param WP_Post $post Post object.
  6527. */
  6528. function _future_post_hook( $deprecated, $post ) {
  6529. wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
  6530. wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT' ), 'publish_future_post', array( $post->ID ) );
  6531. }
  6532. /**
  6533. * Hook to schedule pings and enclosures when a post is published.
  6534. *
  6535. * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
  6536. *
  6537. * @since 2.3.0
  6538. * @access private
  6539. *
  6540. * @param int $post_id The ID in the database table of the post being published.
  6541. */
  6542. function _publish_post_hook( $post_id ) {
  6543. if ( defined( 'XMLRPC_REQUEST' ) ) {
  6544. /**
  6545. * Fires when _publish_post_hook() is called during an XML-RPC request.
  6546. *
  6547. * @since 2.1.0
  6548. *
  6549. * @param int $post_id Post ID.
  6550. */
  6551. do_action( 'xmlrpc_publish_post', $post_id );
  6552. }
  6553. if ( defined( 'WP_IMPORTING' ) ) {
  6554. return;
  6555. }
  6556. if ( get_option( 'default_pingback_flag' ) ) {
  6557. add_post_meta( $post_id, '_pingme', '1', true );
  6558. }
  6559. add_post_meta( $post_id, '_encloseme', '1', true );
  6560. $to_ping = get_to_ping( $post_id );
  6561. if ( ! empty( $to_ping ) ) {
  6562. add_post_meta( $post_id, '_trackbackme', '1' );
  6563. }
  6564. if ( ! wp_next_scheduled( 'do_pings' ) ) {
  6565. wp_schedule_single_event( time(), 'do_pings' );
  6566. }
  6567. }
  6568. /**
  6569. * Returns the ID of the post's parent.
  6570. *
  6571. * @since 3.1.0
  6572. *
  6573. * @param int|WP_Post $post Post ID or post object. Defaults to global $post.
  6574. * @return int|false Post parent ID (which can be 0 if there is no parent),
  6575. * or false if the post does not exist.
  6576. */
  6577. function wp_get_post_parent_id( $post ) {
  6578. $post = get_post( $post );
  6579. if ( ! $post || is_wp_error( $post ) ) {
  6580. return false;
  6581. }
  6582. return (int) $post->post_parent;
  6583. }
  6584. /**
  6585. * Check the given subset of the post hierarchy for hierarchy loops.
  6586. *
  6587. * Prevents loops from forming and breaks those that it finds. Attached
  6588. * to the {@see 'wp_insert_post_parent'} filter.
  6589. *
  6590. * @since 3.1.0
  6591. *
  6592. * @see wp_find_hierarchy_loop()
  6593. *
  6594. * @param int $post_parent ID of the parent for the post we're checking.
  6595. * @param int $post_ID ID of the post we're checking.
  6596. * @return int The new post_parent for the post, 0 otherwise.
  6597. */
  6598. function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
  6599. // Nothing fancy here - bail.
  6600. if ( ! $post_parent ) {
  6601. return 0;
  6602. }
  6603. // New post can't cause a loop.
  6604. if ( ! $post_ID ) {
  6605. return $post_parent;
  6606. }
  6607. // Can't be its own parent.
  6608. if ( $post_parent == $post_ID ) {
  6609. return 0;
  6610. }
  6611. // Now look for larger loops.
  6612. $loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent );
  6613. if ( ! $loop ) {
  6614. return $post_parent; // No loop.
  6615. }
  6616. // Setting $post_parent to the given value causes a loop.
  6617. if ( isset( $loop[ $post_ID ] ) ) {
  6618. return 0;
  6619. }
  6620. // There's a loop, but it doesn't contain $post_ID. Break the loop.
  6621. foreach ( array_keys( $loop ) as $loop_member ) {
  6622. wp_update_post(
  6623. array(
  6624. 'ID' => $loop_member,
  6625. 'post_parent' => 0,
  6626. )
  6627. );
  6628. }
  6629. return $post_parent;
  6630. }
  6631. /**
  6632. * Sets the post thumbnail (featured image) for the given post.
  6633. *
  6634. * @since 3.1.0
  6635. *
  6636. * @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
  6637. * @param int $thumbnail_id Thumbnail to attach.
  6638. * @return int|bool True on success, false on failure.
  6639. */
  6640. function set_post_thumbnail( $post, $thumbnail_id ) {
  6641. $post = get_post( $post );
  6642. $thumbnail_id = absint( $thumbnail_id );
  6643. if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
  6644. if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) {
  6645. return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
  6646. } else {
  6647. return delete_post_meta( $post->ID, '_thumbnail_id' );
  6648. }
  6649. }
  6650. return false;
  6651. }
  6652. /**
  6653. * Removes the thumbnail (featured image) from the given post.
  6654. *
  6655. * @since 3.3.0
  6656. *
  6657. * @param int|WP_Post $post Post ID or post object from which the thumbnail should be removed.
  6658. * @return bool True on success, false on failure.
  6659. */
  6660. function delete_post_thumbnail( $post ) {
  6661. $post = get_post( $post );
  6662. if ( $post ) {
  6663. return delete_post_meta( $post->ID, '_thumbnail_id' );
  6664. }
  6665. return false;
  6666. }
  6667. /**
  6668. * Delete auto-drafts for new posts that are > 7 days old.
  6669. *
  6670. * @since 3.4.0
  6671. *
  6672. * @global wpdb $wpdb WordPress database abstraction object.
  6673. */
  6674. function wp_delete_auto_drafts() {
  6675. global $wpdb;
  6676. // Cleanup old auto-drafts more than 7 days old.
  6677. $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
  6678. foreach ( (array) $old_posts as $delete ) {
  6679. // Force delete.
  6680. wp_delete_post( $delete, true );
  6681. }
  6682. }
  6683. /**
  6684. * Queues posts for lazy-loading of term meta.
  6685. *
  6686. * @since 4.5.0
  6687. *
  6688. * @param array $posts Array of WP_Post objects.
  6689. */
  6690. function wp_queue_posts_for_term_meta_lazyload( $posts ) {
  6691. $post_type_taxonomies = array();
  6692. $term_ids = array();
  6693. foreach ( $posts as $post ) {
  6694. if ( ! ( $post instanceof WP_Post ) ) {
  6695. continue;
  6696. }
  6697. if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
  6698. $post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
  6699. }
  6700. foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
  6701. // Term cache should already be primed by `update_post_term_cache()`.
  6702. $terms = get_object_term_cache( $post->ID, $taxonomy );
  6703. if ( false !== $terms ) {
  6704. foreach ( $terms as $term ) {
  6705. if ( ! in_array( $term->term_id, $term_ids, true ) ) {
  6706. $term_ids[] = $term->term_id;
  6707. }
  6708. }
  6709. }
  6710. }
  6711. }
  6712. if ( $term_ids ) {
  6713. $lazyloader = wp_metadata_lazyloader();
  6714. $lazyloader->queue_objects( 'term', $term_ids );
  6715. }
  6716. }
  6717. /**
  6718. * Update the custom taxonomies' term counts when a post's status is changed.
  6719. *
  6720. * For example, default posts term counts (for custom taxonomies) don't include
  6721. * private / draft posts.
  6722. *
  6723. * @since 3.3.0
  6724. * @access private
  6725. *
  6726. * @param string $new_status New post status.
  6727. * @param string $old_status Old post status.
  6728. * @param WP_Post $post Post object.
  6729. */
  6730. function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
  6731. // Update counts for the post's terms.
  6732. foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
  6733. $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
  6734. wp_update_term_count( $tt_ids, $taxonomy );
  6735. }
  6736. }
  6737. /**
  6738. * Adds any posts from the given IDs to the cache that do not already exist in cache.
  6739. *
  6740. * @since 3.4.0
  6741. * @access private
  6742. *
  6743. * @see update_post_caches()
  6744. *
  6745. * @global wpdb $wpdb WordPress database abstraction object.
  6746. *
  6747. * @param array $ids ID list.
  6748. * @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
  6749. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  6750. */
  6751. function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
  6752. global $wpdb;
  6753. $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
  6754. if ( ! empty( $non_cached_ids ) ) {
  6755. $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
  6756. update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
  6757. }
  6758. }
  6759. /**
  6760. * Adds a suffix if any trashed posts have a given slug.
  6761. *
  6762. * Store its desired (i.e. current) slug so it can try to reclaim it
  6763. * if the post is untrashed.
  6764. *
  6765. * For internal use.
  6766. *
  6767. * @since 4.5.0
  6768. * @access private
  6769. *
  6770. * @param string $post_name Slug.
  6771. * @param int $post_ID Optional. Post ID that should be ignored. Default 0.
  6772. */
  6773. function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_ID = 0 ) {
  6774. $trashed_posts_with_desired_slug = get_posts(
  6775. array(
  6776. 'name' => $post_name,
  6777. 'post_status' => 'trash',
  6778. 'post_type' => 'any',
  6779. 'nopaging' => true,
  6780. 'post__not_in' => array( $post_ID ),
  6781. )
  6782. );
  6783. if ( ! empty( $trashed_posts_with_desired_slug ) ) {
  6784. foreach ( $trashed_posts_with_desired_slug as $_post ) {
  6785. wp_add_trashed_suffix_to_post_name_for_post( $_post );
  6786. }
  6787. }
  6788. }
  6789. /**
  6790. * Adds a trashed suffix for a given post.
  6791. *
  6792. * Store its desired (i.e. current) slug so it can try to reclaim it
  6793. * if the post is untrashed.
  6794. *
  6795. * For internal use.
  6796. *
  6797. * @since 4.5.0
  6798. * @access private
  6799. *
  6800. * @param WP_Post $post The post.
  6801. * @return string New slug for the post.
  6802. */
  6803. function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
  6804. global $wpdb;
  6805. $post = get_post( $post );
  6806. if ( '__trashed' === substr( $post->post_name, -9 ) ) {
  6807. return $post->post_name;
  6808. }
  6809. add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
  6810. $post_name = _truncate_post_slug( $post->post_name, 191 ) . '__trashed';
  6811. $wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
  6812. clean_post_cache( $post->ID );
  6813. return $post_name;
  6814. }
  6815. /**
  6816. * Filters the SQL clauses of an attachment query to include filenames.
  6817. *
  6818. * @since 4.7.0
  6819. * @access private
  6820. *
  6821. * @global wpdb $wpdb WordPress database abstraction object.
  6822. *
  6823. * @param string[] $clauses An array including WHERE, GROUP BY, JOIN, ORDER BY,
  6824. * DISTINCT, fields (SELECT), and LIMITS clauses.
  6825. * @return string[] The modified array of clauses.
  6826. */
  6827. function _filter_query_attachment_filenames( $clauses ) {
  6828. global $wpdb;
  6829. remove_filter( 'posts_clauses', __FUNCTION__ );
  6830. // Add a LEFT JOIN of the postmeta table so we don't trample existing JOINs.
  6831. $clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS sq1 ON ( {$wpdb->posts}.ID = sq1.post_id AND sq1.meta_key = '_wp_attached_file' )";
  6832. $clauses['groupby'] = "{$wpdb->posts}.ID";
  6833. $clauses['where'] = preg_replace(
  6834. "/\({$wpdb->posts}.post_content (NOT LIKE|LIKE) (\'[^']+\')\)/",
  6835. '$0 OR ( sq1.meta_value $1 $2 )',
  6836. $clauses['where']
  6837. );
  6838. return $clauses;
  6839. }
  6840. /**
  6841. * Sets the last changed time for the 'posts' cache group.
  6842. *
  6843. * @since 5.0.0
  6844. */
  6845. function wp_cache_set_posts_last_changed() {
  6846. wp_cache_set( 'last_changed', microtime(), 'posts' );
  6847. }
  6848. /**
  6849. * Get all available post MIME types for a given post type.
  6850. *
  6851. * @since 2.5.0
  6852. *
  6853. * @global wpdb $wpdb WordPress database abstraction object.
  6854. *
  6855. * @param string $type
  6856. * @return mixed
  6857. */
  6858. function get_available_post_mime_types( $type = 'attachment' ) {
  6859. global $wpdb;
  6860. $types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type ) );
  6861. return $types;
  6862. }
  6863. /**
  6864. * Retrieves the path to an uploaded image file.
  6865. *
  6866. * Similar to `get_attached_file()` however some images may have been processed after uploading
  6867. * to make them suitable for web use. In this case the attached "full" size file is usually replaced
  6868. * with a scaled down version of the original image. This function always returns the path
  6869. * to the originally uploaded image file.
  6870. *
  6871. * @since 5.3.0
  6872. * @since 5.4.0 Added the `$unfiltered` parameter.
  6873. *
  6874. * @param int $attachment_id Attachment ID.
  6875. * @param bool $unfiltered Optional. Passed through to `get_attached_file()`. Default false.
  6876. * @return string|false Path to the original image file or false if the attachment is not an image.
  6877. */
  6878. function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
  6879. if ( ! wp_attachment_is_image( $attachment_id ) ) {
  6880. return false;
  6881. }
  6882. $image_meta = wp_get_attachment_metadata( $attachment_id );
  6883. $image_file = get_attached_file( $attachment_id, $unfiltered );
  6884. if ( empty( $image_meta['original_image'] ) ) {
  6885. $original_image = $image_file;
  6886. } else {
  6887. $original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
  6888. }
  6889. /**
  6890. * Filters the path to the original image.
  6891. *
  6892. * @since 5.3.0
  6893. *
  6894. * @param string $original_image Path to original image file.
  6895. * @param int $attachment_id Attachment ID.
  6896. */
  6897. return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
  6898. }
  6899. /**
  6900. * Retrieve the URL to an original attachment image.
  6901. *
  6902. * Similar to `wp_get_attachment_url()` however some images may have been
  6903. * processed after uploading. In this case this function returns the URL
  6904. * to the originally uploaded image file.
  6905. *
  6906. * @since 5.3.0
  6907. *
  6908. * @param int $attachment_id Attachment post ID.
  6909. * @return string|false Attachment image URL, false on error or if the attachment is not an image.
  6910. */
  6911. function wp_get_original_image_url( $attachment_id ) {
  6912. if ( ! wp_attachment_is_image( $attachment_id ) ) {
  6913. return false;
  6914. }
  6915. $image_url = wp_get_attachment_url( $attachment_id );
  6916. if ( ! $image_url ) {
  6917. return false;
  6918. }
  6919. $image_meta = wp_get_attachment_metadata( $attachment_id );
  6920. if ( empty( $image_meta['original_image'] ) ) {
  6921. $original_image_url = $image_url;
  6922. } else {
  6923. $original_image_url = path_join( dirname( $image_url ), $image_meta['original_image'] );
  6924. }
  6925. /**
  6926. * Filters the URL to the original attachment image.
  6927. *
  6928. * @since 5.3.0
  6929. *
  6930. * @param string $original_image_url URL to original image.
  6931. * @param int $attachment_id Attachment ID.
  6932. */
  6933. return apply_filters( 'wp_get_original_image_url', $original_image_url, $attachment_id );
  6934. }
  6935. /**
  6936. * Filter callback which sets the status of an untrashed post to its previous status.
  6937. *
  6938. * This can be used as a callback on the `wp_untrash_post_status` filter.
  6939. *
  6940. * @since 5.6.0
  6941. *
  6942. * @param string $new_status The new status of the post being restored.
  6943. * @param int $post_id The ID of the post being restored.
  6944. * @param string $previous_status The status of the post at the point where it was trashed.
  6945. * @return string The new status of the post.
  6946. */
  6947. function wp_untrash_post_set_previous_status( $new_status, $post_id, $previous_status ) {
  6948. return $previous_status;
  6949. }