post.php 236 KB

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