post.php 215 KB

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