post.php 207 KB

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