taxonomy.php 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039
  1. <?php
  2. /**
  3. * Core Taxonomy API
  4. *
  5. * @package WordPress
  6. * @subpackage Taxonomy
  7. */
  8. //
  9. // Taxonomy registration.
  10. //
  11. /**
  12. * Creates the initial taxonomies.
  13. *
  14. * This function fires twice: in wp-settings.php before plugins are loaded (for
  15. * backward compatibility reasons), and again on the {@see 'init'} action. We must
  16. * avoid registering rewrite rules before the {@see 'init'} action.
  17. *
  18. * @since 2.8.0
  19. * @since 5.9.0 Added `'wp_template_part_area'` taxonomy.
  20. *
  21. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  22. */
  23. function create_initial_taxonomies() {
  24. global $wp_rewrite;
  25. WP_Taxonomy::reset_default_labels();
  26. if ( ! did_action( 'init' ) ) {
  27. $rewrite = array(
  28. 'category' => false,
  29. 'post_tag' => false,
  30. 'post_format' => false,
  31. );
  32. } else {
  33. /**
  34. * Filters the post formats rewrite base.
  35. *
  36. * @since 3.1.0
  37. *
  38. * @param string $context Context of the rewrite base. Default 'type'.
  39. */
  40. $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
  41. $rewrite = array(
  42. 'category' => array(
  43. 'hierarchical' => true,
  44. 'slug' => get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category',
  45. 'with_front' => ! get_option( 'category_base' ) || $wp_rewrite->using_index_permalinks(),
  46. 'ep_mask' => EP_CATEGORIES,
  47. ),
  48. 'post_tag' => array(
  49. 'hierarchical' => false,
  50. 'slug' => get_option( 'tag_base' ) ? get_option( 'tag_base' ) : 'tag',
  51. 'with_front' => ! get_option( 'tag_base' ) || $wp_rewrite->using_index_permalinks(),
  52. 'ep_mask' => EP_TAGS,
  53. ),
  54. 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
  55. );
  56. }
  57. register_taxonomy(
  58. 'category',
  59. 'post',
  60. array(
  61. 'hierarchical' => true,
  62. 'query_var' => 'category_name',
  63. 'rewrite' => $rewrite['category'],
  64. 'public' => true,
  65. 'show_ui' => true,
  66. 'show_admin_column' => true,
  67. '_builtin' => true,
  68. 'capabilities' => array(
  69. 'manage_terms' => 'manage_categories',
  70. 'edit_terms' => 'edit_categories',
  71. 'delete_terms' => 'delete_categories',
  72. 'assign_terms' => 'assign_categories',
  73. ),
  74. 'show_in_rest' => true,
  75. 'rest_base' => 'categories',
  76. 'rest_controller_class' => 'WP_REST_Terms_Controller',
  77. )
  78. );
  79. register_taxonomy(
  80. 'post_tag',
  81. 'post',
  82. array(
  83. 'hierarchical' => false,
  84. 'query_var' => 'tag',
  85. 'rewrite' => $rewrite['post_tag'],
  86. 'public' => true,
  87. 'show_ui' => true,
  88. 'show_admin_column' => true,
  89. '_builtin' => true,
  90. 'capabilities' => array(
  91. 'manage_terms' => 'manage_post_tags',
  92. 'edit_terms' => 'edit_post_tags',
  93. 'delete_terms' => 'delete_post_tags',
  94. 'assign_terms' => 'assign_post_tags',
  95. ),
  96. 'show_in_rest' => true,
  97. 'rest_base' => 'tags',
  98. 'rest_controller_class' => 'WP_REST_Terms_Controller',
  99. )
  100. );
  101. register_taxonomy(
  102. 'nav_menu',
  103. 'nav_menu_item',
  104. array(
  105. 'public' => false,
  106. 'hierarchical' => false,
  107. 'labels' => array(
  108. 'name' => __( 'Navigation Menus' ),
  109. 'singular_name' => __( 'Navigation Menu' ),
  110. ),
  111. 'query_var' => false,
  112. 'rewrite' => false,
  113. 'show_ui' => false,
  114. '_builtin' => true,
  115. 'show_in_nav_menus' => false,
  116. 'capabilities' => array(
  117. 'manage_terms' => 'edit_theme_options',
  118. 'edit_terms' => 'edit_theme_options',
  119. 'delete_terms' => 'edit_theme_options',
  120. 'assign_terms' => 'edit_theme_options',
  121. ),
  122. 'show_in_rest' => true,
  123. 'rest_base' => 'menus',
  124. 'rest_controller_class' => 'WP_REST_Menus_Controller',
  125. )
  126. );
  127. register_taxonomy(
  128. 'link_category',
  129. 'link',
  130. array(
  131. 'hierarchical' => false,
  132. 'labels' => array(
  133. 'name' => __( 'Link Categories' ),
  134. 'singular_name' => __( 'Link Category' ),
  135. 'search_items' => __( 'Search Link Categories' ),
  136. 'popular_items' => null,
  137. 'all_items' => __( 'All Link Categories' ),
  138. 'edit_item' => __( 'Edit Link Category' ),
  139. 'update_item' => __( 'Update Link Category' ),
  140. 'add_new_item' => __( 'Add New Link Category' ),
  141. 'new_item_name' => __( 'New Link Category Name' ),
  142. 'separate_items_with_commas' => null,
  143. 'add_or_remove_items' => null,
  144. 'choose_from_most_used' => null,
  145. 'back_to_items' => __( '&larr; Go to Link Categories' ),
  146. ),
  147. 'capabilities' => array(
  148. 'manage_terms' => 'manage_links',
  149. 'edit_terms' => 'manage_links',
  150. 'delete_terms' => 'manage_links',
  151. 'assign_terms' => 'manage_links',
  152. ),
  153. 'query_var' => false,
  154. 'rewrite' => false,
  155. 'public' => false,
  156. 'show_ui' => true,
  157. '_builtin' => true,
  158. )
  159. );
  160. register_taxonomy(
  161. 'post_format',
  162. 'post',
  163. array(
  164. 'public' => true,
  165. 'hierarchical' => false,
  166. 'labels' => array(
  167. 'name' => _x( 'Formats', 'post format' ),
  168. 'singular_name' => _x( 'Format', 'post format' ),
  169. ),
  170. 'query_var' => true,
  171. 'rewrite' => $rewrite['post_format'],
  172. 'show_ui' => false,
  173. '_builtin' => true,
  174. 'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
  175. )
  176. );
  177. register_taxonomy(
  178. 'wp_theme',
  179. array( 'wp_template', 'wp_template_part', 'wp_global_styles' ),
  180. array(
  181. 'public' => false,
  182. 'hierarchical' => false,
  183. 'labels' => array(
  184. 'name' => __( 'Themes' ),
  185. 'singular_name' => __( 'Theme' ),
  186. ),
  187. 'query_var' => false,
  188. 'rewrite' => false,
  189. 'show_ui' => false,
  190. '_builtin' => true,
  191. 'show_in_nav_menus' => false,
  192. 'show_in_rest' => false,
  193. )
  194. );
  195. register_taxonomy(
  196. 'wp_template_part_area',
  197. array( 'wp_template_part' ),
  198. array(
  199. 'public' => false,
  200. 'hierarchical' => false,
  201. 'labels' => array(
  202. 'name' => __( 'Template Part Areas' ),
  203. 'singular_name' => __( 'Template Part Area' ),
  204. ),
  205. 'query_var' => false,
  206. 'rewrite' => false,
  207. 'show_ui' => false,
  208. '_builtin' => true,
  209. 'show_in_nav_menus' => false,
  210. 'show_in_rest' => false,
  211. )
  212. );
  213. }
  214. /**
  215. * Retrieves a list of registered taxonomy names or objects.
  216. *
  217. * @since 3.0.0
  218. *
  219. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  220. *
  221. * @param array $args Optional. An array of `key => value` arguments to match against the taxonomy objects.
  222. * Default empty array.
  223. * @param string $output Optional. The type of output to return in the array. Accepts either taxonomy 'names'
  224. * or 'objects'. Default 'names'.
  225. * @param string $operator Optional. The logical operation to perform. Accepts 'and' or 'or'. 'or' means only
  226. * one element from the array needs to match; 'and' means all elements must match.
  227. * Default 'and'.
  228. * @return string[]|WP_Taxonomy[] An array of taxonomy names or objects.
  229. */
  230. function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
  231. global $wp_taxonomies;
  232. $field = ( 'names' === $output ) ? 'name' : false;
  233. return wp_filter_object_list( $wp_taxonomies, $args, $operator, $field );
  234. }
  235. /**
  236. * Returns the names or objects of the taxonomies which are registered for the requested object or object type,
  237. * such as a post object or post type name.
  238. *
  239. * Example:
  240. *
  241. * $taxonomies = get_object_taxonomies( 'post' );
  242. *
  243. * This results in:
  244. *
  245. * Array( 'category', 'post_tag' )
  246. *
  247. * @since 2.3.0
  248. *
  249. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  250. *
  251. * @param string|string[]|WP_Post $object Name of the type of taxonomy object, or an object (row from posts)
  252. * @param string $output Optional. The type of output to return in the array. Accepts either
  253. * 'names' or 'objects'. Default 'names'.
  254. * @return string[]|WP_Taxonomy[] The names or objects of all taxonomies of `$object_type`.
  255. */
  256. function get_object_taxonomies( $object, $output = 'names' ) {
  257. global $wp_taxonomies;
  258. if ( is_object( $object ) ) {
  259. if ( 'attachment' === $object->post_type ) {
  260. return get_attachment_taxonomies( $object, $output );
  261. }
  262. $object = $object->post_type;
  263. }
  264. $object = (array) $object;
  265. $taxonomies = array();
  266. foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
  267. if ( array_intersect( $object, (array) $tax_obj->object_type ) ) {
  268. if ( 'names' === $output ) {
  269. $taxonomies[] = $tax_name;
  270. } else {
  271. $taxonomies[ $tax_name ] = $tax_obj;
  272. }
  273. }
  274. }
  275. return $taxonomies;
  276. }
  277. /**
  278. * Retrieves the taxonomy object of $taxonomy.
  279. *
  280. * The get_taxonomy function will first check that the parameter string given
  281. * is a taxonomy object and if it is, it will return it.
  282. *
  283. * @since 2.3.0
  284. *
  285. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  286. *
  287. * @param string $taxonomy Name of taxonomy object to return.
  288. * @return WP_Taxonomy|false The taxonomy object or false if $taxonomy doesn't exist.
  289. */
  290. function get_taxonomy( $taxonomy ) {
  291. global $wp_taxonomies;
  292. if ( ! taxonomy_exists( $taxonomy ) ) {
  293. return false;
  294. }
  295. return $wp_taxonomies[ $taxonomy ];
  296. }
  297. /**
  298. * Determines whether the taxonomy name exists.
  299. *
  300. * Formerly is_taxonomy(), introduced in 2.3.0.
  301. *
  302. * For more information on this and similar theme functions, check out
  303. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  304. * Conditional Tags} article in the Theme Developer Handbook.
  305. *
  306. * @since 3.0.0
  307. *
  308. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  309. *
  310. * @param string $taxonomy Name of taxonomy object.
  311. * @return bool Whether the taxonomy exists.
  312. */
  313. function taxonomy_exists( $taxonomy ) {
  314. global $wp_taxonomies;
  315. return is_string( $taxonomy ) && isset( $wp_taxonomies[ $taxonomy ] );
  316. }
  317. /**
  318. * Determines whether the taxonomy object is hierarchical.
  319. *
  320. * Checks to make sure that the taxonomy is an object first. Then Gets the
  321. * object, and finally returns the hierarchical value in the object.
  322. *
  323. * A false return value might also mean that the taxonomy does not exist.
  324. *
  325. * For more information on this and similar theme functions, check out
  326. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  327. * Conditional Tags} article in the Theme Developer Handbook.
  328. *
  329. * @since 2.3.0
  330. *
  331. * @param string $taxonomy Name of taxonomy object.
  332. * @return bool Whether the taxonomy is hierarchical.
  333. */
  334. function is_taxonomy_hierarchical( $taxonomy ) {
  335. if ( ! taxonomy_exists( $taxonomy ) ) {
  336. return false;
  337. }
  338. $taxonomy = get_taxonomy( $taxonomy );
  339. return $taxonomy->hierarchical;
  340. }
  341. /**
  342. * Creates or modifies a taxonomy object.
  343. *
  344. * Note: Do not use before the {@see 'init'} hook.
  345. *
  346. * A simple function for creating or modifying a taxonomy object based on
  347. * the parameters given. If modifying an existing taxonomy object, note
  348. * that the `$object_type` value from the original registration will be
  349. * overwritten.
  350. *
  351. * @since 2.3.0
  352. * @since 4.2.0 Introduced `show_in_quick_edit` argument.
  353. * @since 4.4.0 The `show_ui` argument is now enforced on the term editing screen.
  354. * @since 4.4.0 The `public` argument now controls whether the taxonomy can be queried on the front end.
  355. * @since 4.5.0 Introduced `publicly_queryable` argument.
  356. * @since 4.7.0 Introduced `show_in_rest`, 'rest_base' and 'rest_controller_class'
  357. * arguments to register the taxonomy in REST API.
  358. * @since 5.1.0 Introduced `meta_box_sanitize_cb` argument.
  359. * @since 5.4.0 Added the registered taxonomy object as a return value.
  360. * @since 5.5.0 Introduced `default_term` argument.
  361. * @since 5.9.0 Introduced `rest_namespace` argument.
  362. *
  363. * @global WP_Taxonomy[] $wp_taxonomies Registered taxonomies.
  364. *
  365. * @param string $taxonomy Taxonomy key, must not exceed 32 characters and may only contain lowercase alphanumeric
  366. * characters, dashes, and underscores. See sanitize_key().
  367. * @param array|string $object_type Object type or array of object types with which the taxonomy should be associated.
  368. * @param array|string $args {
  369. * Optional. Array or query string of arguments for registering a taxonomy.
  370. *
  371. * @type string[] $labels An array of labels for this taxonomy. By default, Tag labels are
  372. * used for non-hierarchical taxonomies, and Category labels are used
  373. * for hierarchical taxonomies. See accepted values in
  374. * get_taxonomy_labels(). Default empty array.
  375. * @type string $description A short descriptive summary of what the taxonomy is for. Default empty.
  376. * @type bool $public Whether a taxonomy is intended for use publicly either via
  377. * the admin interface or by front-end users. The default settings
  378. * of `$publicly_queryable`, `$show_ui`, and `$show_in_nav_menus`
  379. * are inherited from `$public`.
  380. * @type bool $publicly_queryable Whether the taxonomy is publicly queryable.
  381. * If not set, the default is inherited from `$public`
  382. * @type bool $hierarchical Whether the taxonomy is hierarchical. Default false.
  383. * @type bool $show_ui Whether to generate and allow a UI for managing terms in this taxonomy in
  384. * the admin. If not set, the default is inherited from `$public`
  385. * (default true).
  386. * @type bool $show_in_menu Whether to show the taxonomy in the admin menu. If true, the taxonomy is
  387. * shown as a submenu of the object type menu. If false, no menu is shown.
  388. * `$show_ui` must be true. If not set, default is inherited from `$show_ui`
  389. * (default true).
  390. * @type bool $show_in_nav_menus Makes this taxonomy available for selection in navigation menus. If not
  391. * set, the default is inherited from `$public` (default true).
  392. * @type bool $show_in_rest Whether to include the taxonomy in the REST API. Set this to true
  393. * for the taxonomy to be available in the block editor.
  394. * @type string $rest_base To change the base url of REST API route. Default is $taxonomy.
  395. * @type string $rest_namespace To change the namespace URL of REST API route. Default is wp/v2.
  396. * @type string $rest_controller_class REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
  397. * @type bool $show_tagcloud Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
  398. * the default is inherited from `$show_ui` (default true).
  399. * @type bool $show_in_quick_edit Whether to show the taxonomy in the quick/bulk edit panel. It not set,
  400. * the default is inherited from `$show_ui` (default true).
  401. * @type bool $show_admin_column Whether to display a column for the taxonomy on its post type listing
  402. * screens. Default false.
  403. * @type bool|callable $meta_box_cb Provide a callback function for the meta box display. If not set,
  404. * post_categories_meta_box() is used for hierarchical taxonomies, and
  405. * post_tags_meta_box() is used for non-hierarchical. If false, no meta
  406. * box is shown.
  407. * @type callable $meta_box_sanitize_cb Callback function for sanitizing taxonomy data saved from a meta
  408. * box. If no callback is defined, an appropriate one is determined
  409. * based on the value of `$meta_box_cb`.
  410. * @type string[] $capabilities {
  411. * Array of capabilities for this taxonomy.
  412. *
  413. * @type string $manage_terms Default 'manage_categories'.
  414. * @type string $edit_terms Default 'manage_categories'.
  415. * @type string $delete_terms Default 'manage_categories'.
  416. * @type string $assign_terms Default 'edit_posts'.
  417. * }
  418. * @type bool|array $rewrite {
  419. * Triggers the handling of rewrites for this taxonomy. Default true, using $taxonomy as slug. To prevent
  420. * rewrite, set to false. To specify rewrite rules, an array can be passed with any of these keys:
  421. *
  422. * @type string $slug Customize the permastruct slug. Default `$taxonomy` key.
  423. * @type bool $with_front Should the permastruct be prepended with WP_Rewrite::$front. Default true.
  424. * @type bool $hierarchical Either hierarchical rewrite tag or not. Default false.
  425. * @type int $ep_mask Assign an endpoint mask. Default `EP_NONE`.
  426. * }
  427. * @type string|bool $query_var Sets the query var key for this taxonomy. Default `$taxonomy` key. If
  428. * false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
  429. * string, the query `?{query_var}={term_slug}` will be valid.
  430. * @type callable $update_count_callback Works much like a hook, in that it will be called when the count is
  431. * updated. Default _update_post_term_count() for taxonomies attached
  432. * to post types, which confirms that the objects are published before
  433. * counting them. Default _update_generic_term_count() for taxonomies
  434. * attached to other object types, such as users.
  435. * @type string|array $default_term {
  436. * Default term to be used for the taxonomy.
  437. *
  438. * @type string $name Name of default term.
  439. * @type string $slug Slug for default term. Default empty.
  440. * @type string $description Description for default term. Default empty.
  441. * }
  442. * @type bool $sort Whether terms in this taxonomy should be sorted in the order they are
  443. * provided to `wp_set_object_terms()`. Default null which equates to false.
  444. * @type array $args Array of arguments to automatically use inside `wp_get_object_terms()`
  445. * for this taxonomy.
  446. * @type bool $_builtin This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
  447. * Default false.
  448. * }
  449. * @return WP_Taxonomy|WP_Error The registered taxonomy object on success, WP_Error object on failure.
  450. */
  451. function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
  452. global $wp_taxonomies;
  453. if ( ! is_array( $wp_taxonomies ) ) {
  454. $wp_taxonomies = array();
  455. }
  456. $args = wp_parse_args( $args );
  457. if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
  458. _doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2.0' );
  459. return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
  460. }
  461. $taxonomy_object = new WP_Taxonomy( $taxonomy, $object_type, $args );
  462. $taxonomy_object->add_rewrite_rules();
  463. $wp_taxonomies[ $taxonomy ] = $taxonomy_object;
  464. $taxonomy_object->add_hooks();
  465. // Add default term.
  466. if ( ! empty( $taxonomy_object->default_term ) ) {
  467. $term = term_exists( $taxonomy_object->default_term['name'], $taxonomy );
  468. if ( $term ) {
  469. update_option( 'default_term_' . $taxonomy_object->name, $term['term_id'] );
  470. } else {
  471. $term = wp_insert_term(
  472. $taxonomy_object->default_term['name'],
  473. $taxonomy,
  474. array(
  475. 'slug' => sanitize_title( $taxonomy_object->default_term['slug'] ),
  476. 'description' => $taxonomy_object->default_term['description'],
  477. )
  478. );
  479. // Update `term_id` in options.
  480. if ( ! is_wp_error( $term ) ) {
  481. update_option( 'default_term_' . $taxonomy_object->name, $term['term_id'] );
  482. }
  483. }
  484. }
  485. /**
  486. * Fires after a taxonomy is registered.
  487. *
  488. * @since 3.3.0
  489. *
  490. * @param string $taxonomy Taxonomy slug.
  491. * @param array|string $object_type Object type or array of object types.
  492. * @param array $args Array of taxonomy registration arguments.
  493. */
  494. do_action( 'registered_taxonomy', $taxonomy, $object_type, (array) $taxonomy_object );
  495. /**
  496. * Fires after a specific taxonomy is registered.
  497. *
  498. * The dynamic portion of the filter name, `$taxonomy`, refers to the taxonomy key.
  499. *
  500. * Possible hook names include:
  501. *
  502. * - `registered_taxonomy_category`
  503. * - `registered_taxonomy_post_tag`
  504. *
  505. * @since 6.0.0
  506. *
  507. * @param string $taxonomy Taxonomy slug.
  508. * @param array|string $object_type Object type or array of object types.
  509. * @param array $args Array of taxonomy registration arguments.
  510. */
  511. do_action( "registered_taxonomy_{$taxonomy}", $taxonomy, $object_type, (array) $taxonomy_object );
  512. return $taxonomy_object;
  513. }
  514. /**
  515. * Unregisters a taxonomy.
  516. *
  517. * Can not be used to unregister built-in taxonomies.
  518. *
  519. * @since 4.5.0
  520. *
  521. * @global WP $wp Current WordPress environment instance.
  522. * @global WP_Taxonomy[] $wp_taxonomies List of taxonomies.
  523. *
  524. * @param string $taxonomy Taxonomy name.
  525. * @return true|WP_Error True on success, WP_Error on failure or if the taxonomy doesn't exist.
  526. */
  527. function unregister_taxonomy( $taxonomy ) {
  528. if ( ! taxonomy_exists( $taxonomy ) ) {
  529. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  530. }
  531. $taxonomy_object = get_taxonomy( $taxonomy );
  532. // Do not allow unregistering internal taxonomies.
  533. if ( $taxonomy_object->_builtin ) {
  534. return new WP_Error( 'invalid_taxonomy', __( 'Unregistering a built-in taxonomy is not allowed.' ) );
  535. }
  536. global $wp_taxonomies;
  537. $taxonomy_object->remove_rewrite_rules();
  538. $taxonomy_object->remove_hooks();
  539. // Remove the taxonomy.
  540. unset( $wp_taxonomies[ $taxonomy ] );
  541. /**
  542. * Fires after a taxonomy is unregistered.
  543. *
  544. * @since 4.5.0
  545. *
  546. * @param string $taxonomy Taxonomy name.
  547. */
  548. do_action( 'unregistered_taxonomy', $taxonomy );
  549. return true;
  550. }
  551. /**
  552. * Builds an object with all taxonomy labels out of a taxonomy object.
  553. *
  554. * @since 3.0.0
  555. * @since 4.3.0 Added the `no_terms` label.
  556. * @since 4.4.0 Added the `items_list_navigation` and `items_list` labels.
  557. * @since 4.9.0 Added the `most_used` and `back_to_items` labels.
  558. * @since 5.7.0 Added the `filter_by_item` label.
  559. * @since 5.8.0 Added the `item_link` and `item_link_description` labels.
  560. * @since 5.9.0 Added the `name_field_description`, `slug_field_description`,
  561. * `parent_field_description`, and `desc_field_description` labels.
  562. *
  563. * @param WP_Taxonomy $tax Taxonomy object.
  564. * @return object {
  565. * Taxonomy labels object. The first default value is for non-hierarchical taxonomies
  566. * (like tags) and the second one is for hierarchical taxonomies (like categories).
  567. *
  568. * @type string $name General name for the taxonomy, usually plural. The same
  569. * as and overridden by `$tax->label`. Default 'Tags'/'Categories'.
  570. * @type string $singular_name Name for one object of this taxonomy. Default 'Tag'/'Category'.
  571. * @type string $search_items Default 'Search Tags'/'Search Categories'.
  572. * @type string $popular_items This label is only used for non-hierarchical taxonomies.
  573. * Default 'Popular Tags'.
  574. * @type string $all_items Default 'All Tags'/'All Categories'.
  575. * @type string $parent_item This label is only used for hierarchical taxonomies. Default
  576. * 'Parent Category'.
  577. * @type string $parent_item_colon The same as `parent_item`, but with colon `:` in the end.
  578. * @type string $name_field_description Description for the Name field on Edit Tags screen.
  579. * Default 'The name is how it appears on your site'.
  580. * @type string $slug_field_description Description for the Slug field on Edit Tags screen.
  581. * Default 'The &#8220;slug&#8221; is the URL-friendly version
  582. * of the name. It is usually all lowercase and contains
  583. * only letters, numbers, and hyphens'.
  584. * @type string $parent_field_description Description for the Parent field on Edit Tags screen.
  585. * Default 'Assign a parent term to create a hierarchy.
  586. * The term Jazz, for example, would be the parent
  587. * of Bebop and Big Band'.
  588. * @type string $desc_field_description Description for the Description field on Edit Tags screen.
  589. * Default 'The description is not prominent by default;
  590. * however, some themes may show it'.
  591. * @type string $edit_item Default 'Edit Tag'/'Edit Category'.
  592. * @type string $view_item Default 'View Tag'/'View Category'.
  593. * @type string $update_item Default 'Update Tag'/'Update Category'.
  594. * @type string $add_new_item Default 'Add New Tag'/'Add New Category'.
  595. * @type string $new_item_name Default 'New Tag Name'/'New Category Name'.
  596. * @type string $separate_items_with_commas This label is only used for non-hierarchical taxonomies. Default
  597. * 'Separate tags with commas', used in the meta box.
  598. * @type string $add_or_remove_items This label is only used for non-hierarchical taxonomies. Default
  599. * 'Add or remove tags', used in the meta box when JavaScript
  600. * is disabled.
  601. * @type string $choose_from_most_used This label is only used on non-hierarchical taxonomies. Default
  602. * 'Choose from the most used tags', used in the meta box.
  603. * @type string $not_found Default 'No tags found'/'No categories found', used in
  604. * the meta box and taxonomy list table.
  605. * @type string $no_terms Default 'No tags'/'No categories', used in the posts and media
  606. * list tables.
  607. * @type string $filter_by_item This label is only used for hierarchical taxonomies. Default
  608. * 'Filter by category', used in the posts list table.
  609. * @type string $items_list_navigation Label for the table pagination hidden heading.
  610. * @type string $items_list Label for the table hidden heading.
  611. * @type string $most_used Title for the Most Used tab. Default 'Most Used'.
  612. * @type string $back_to_items Label displayed after a term has been updated.
  613. * @type string $item_link Used in the block editor. Title for a navigation link block variation.
  614. * Default 'Tag Link'/'Category Link'.
  615. * @type string $item_link_description Used in the block editor. Description for a navigation link block
  616. * variation. Default 'A link to a tag'/'A link to a category'.
  617. * }
  618. */
  619. function get_taxonomy_labels( $tax ) {
  620. $tax->labels = (array) $tax->labels;
  621. if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) ) {
  622. $tax->labels['separate_items_with_commas'] = $tax->helps;
  623. }
  624. if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) ) {
  625. $tax->labels['not_found'] = $tax->no_tagcloud;
  626. }
  627. $nohier_vs_hier_defaults = WP_Taxonomy::get_default_labels();
  628. $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
  629. $labels = _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
  630. $taxonomy = $tax->name;
  631. $default_labels = clone $labels;
  632. /**
  633. * Filters the labels of a specific taxonomy.
  634. *
  635. * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
  636. *
  637. * Possible hook names include:
  638. *
  639. * - `taxonomy_labels_category`
  640. * - `taxonomy_labels_post_tag`
  641. *
  642. * @since 4.4.0
  643. *
  644. * @see get_taxonomy_labels() for the full list of taxonomy labels.
  645. *
  646. * @param object $labels Object with labels for the taxonomy as member variables.
  647. */
  648. $labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );
  649. // Ensure that the filtered labels contain all required default values.
  650. $labels = (object) array_merge( (array) $default_labels, (array) $labels );
  651. return $labels;
  652. }
  653. /**
  654. * Adds an already registered taxonomy to an object type.
  655. *
  656. * @since 3.0.0
  657. *
  658. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  659. *
  660. * @param string $taxonomy Name of taxonomy object.
  661. * @param string $object_type Name of the object type.
  662. * @return bool True if successful, false if not.
  663. */
  664. function register_taxonomy_for_object_type( $taxonomy, $object_type ) {
  665. global $wp_taxonomies;
  666. if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
  667. return false;
  668. }
  669. if ( ! get_post_type_object( $object_type ) ) {
  670. return false;
  671. }
  672. if ( ! in_array( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true ) ) {
  673. $wp_taxonomies[ $taxonomy ]->object_type[] = $object_type;
  674. }
  675. // Filter out empties.
  676. $wp_taxonomies[ $taxonomy ]->object_type = array_filter( $wp_taxonomies[ $taxonomy ]->object_type );
  677. /**
  678. * Fires after a taxonomy is registered for an object type.
  679. *
  680. * @since 5.1.0
  681. *
  682. * @param string $taxonomy Taxonomy name.
  683. * @param string $object_type Name of the object type.
  684. */
  685. do_action( 'registered_taxonomy_for_object_type', $taxonomy, $object_type );
  686. return true;
  687. }
  688. /**
  689. * Removes an already registered taxonomy from an object type.
  690. *
  691. * @since 3.7.0
  692. *
  693. * @global WP_Taxonomy[] $wp_taxonomies The registered taxonomies.
  694. *
  695. * @param string $taxonomy Name of taxonomy object.
  696. * @param string $object_type Name of the object type.
  697. * @return bool True if successful, false if not.
  698. */
  699. function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
  700. global $wp_taxonomies;
  701. if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
  702. return false;
  703. }
  704. if ( ! get_post_type_object( $object_type ) ) {
  705. return false;
  706. }
  707. $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
  708. if ( false === $key ) {
  709. return false;
  710. }
  711. unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
  712. /**
  713. * Fires after a taxonomy is unregistered for an object type.
  714. *
  715. * @since 5.1.0
  716. *
  717. * @param string $taxonomy Taxonomy name.
  718. * @param string $object_type Name of the object type.
  719. */
  720. do_action( 'unregistered_taxonomy_for_object_type', $taxonomy, $object_type );
  721. return true;
  722. }
  723. //
  724. // Term API.
  725. //
  726. /**
  727. * Retrieves object IDs of valid taxonomy and term.
  728. *
  729. * The strings of `$taxonomies` must exist before this function will continue.
  730. * On failure of finding a valid taxonomy, it will return a WP_Error.
  731. *
  732. * The `$terms` aren't checked the same as `$taxonomies`, but still need to exist
  733. * for object IDs to be returned.
  734. *
  735. * It is possible to change the order that object IDs are returned by using `$args`
  736. * with either ASC or DESC array. The value should be in the key named 'order'.
  737. *
  738. * @since 2.3.0
  739. *
  740. * @global wpdb $wpdb WordPress database abstraction object.
  741. *
  742. * @param int|int[] $term_ids Term ID or array of term IDs of terms that will be used.
  743. * @param string|string[] $taxonomies String of taxonomy name or Array of string values of taxonomy names.
  744. * @param array|string $args Change the order of the object IDs, either ASC or DESC.
  745. * @return string[]|WP_Error An array of object IDs as numeric strings on success,
  746. * WP_Error if the taxonomy does not exist.
  747. */
  748. function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
  749. global $wpdb;
  750. if ( ! is_array( $term_ids ) ) {
  751. $term_ids = array( $term_ids );
  752. }
  753. if ( ! is_array( $taxonomies ) ) {
  754. $taxonomies = array( $taxonomies );
  755. }
  756. foreach ( (array) $taxonomies as $taxonomy ) {
  757. if ( ! taxonomy_exists( $taxonomy ) ) {
  758. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  759. }
  760. }
  761. $defaults = array( 'order' => 'ASC' );
  762. $args = wp_parse_args( $args, $defaults );
  763. $order = ( 'desc' === strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
  764. $term_ids = array_map( 'intval', $term_ids );
  765. $taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
  766. $term_ids = "'" . implode( "', '", $term_ids ) . "'";
  767. $sql = "SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order";
  768. $last_changed = wp_cache_get_last_changed( 'terms' );
  769. $cache_key = 'get_objects_in_term:' . md5( $sql ) . ":$last_changed";
  770. $cache = wp_cache_get( $cache_key, 'terms' );
  771. if ( false === $cache ) {
  772. $object_ids = $wpdb->get_col( $sql );
  773. wp_cache_set( $cache_key, $object_ids, 'terms' );
  774. } else {
  775. $object_ids = (array) $cache;
  776. }
  777. if ( ! $object_ids ) {
  778. return array();
  779. }
  780. return $object_ids;
  781. }
  782. /**
  783. * Given a taxonomy query, generates SQL to be appended to a main query.
  784. *
  785. * @since 3.1.0
  786. *
  787. * @see WP_Tax_Query
  788. *
  789. * @param array $tax_query A compact tax query
  790. * @param string $primary_table
  791. * @param string $primary_id_column
  792. * @return string[]
  793. */
  794. function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
  795. $tax_query_obj = new WP_Tax_Query( $tax_query );
  796. return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
  797. }
  798. /**
  799. * Gets all term data from database by term ID.
  800. *
  801. * The usage of the get_term function is to apply filters to a term object. It
  802. * is possible to get a term object from the database before applying the
  803. * filters.
  804. *
  805. * $term ID must be part of $taxonomy, to get from the database. Failure, might
  806. * be able to be captured by the hooks. Failure would be the same value as $wpdb
  807. * returns for the get_row method.
  808. *
  809. * There are two hooks, one is specifically for each term, named 'get_term', and
  810. * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
  811. * term object, and the taxonomy name as parameters. Both hooks are expected to
  812. * return a term object.
  813. *
  814. * {@see 'get_term'} hook - Takes two parameters the term Object and the taxonomy name.
  815. * Must return term object. Used in get_term() as a catch-all filter for every
  816. * $term.
  817. *
  818. * {@see 'get_$taxonomy'} hook - Takes two parameters the term Object and the taxonomy
  819. * name. Must return term object. $taxonomy will be the taxonomy name, so for
  820. * example, if 'category', it would be 'get_category' as the filter name. Useful
  821. * for custom taxonomies or plugging into default taxonomies.
  822. *
  823. * @todo Better formatting for DocBlock
  824. *
  825. * @since 2.3.0
  826. * @since 4.4.0 Converted to return a WP_Term object if `$output` is `OBJECT`.
  827. * The `$taxonomy` parameter was made optional.
  828. *
  829. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  830. *
  831. * @param int|WP_Term|object $term If integer, term data will be fetched from the database,
  832. * or from the cache if available.
  833. * If stdClass object (as in the results of a database query),
  834. * will apply filters and return a `WP_Term` object with the `$term` data.
  835. * If `WP_Term`, will return `$term`.
  836. * @param string $taxonomy Optional. Taxonomy name that `$term` is part of.
  837. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  838. * correspond to a WP_Term object, an associative array, or a numeric array,
  839. * respectively. Default OBJECT.
  840. * @param string $filter Optional. How to sanitize term fields. Default 'raw'.
  841. * @return WP_Term|array|WP_Error|null WP_Term instance (or array) on success, depending on the `$output` value.
  842. * WP_Error if `$taxonomy` does not exist. Null for miscellaneous failure.
  843. */
  844. function get_term( $term, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
  845. if ( empty( $term ) ) {
  846. return new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
  847. }
  848. if ( $taxonomy && ! taxonomy_exists( $taxonomy ) ) {
  849. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  850. }
  851. if ( $term instanceof WP_Term ) {
  852. $_term = $term;
  853. } elseif ( is_object( $term ) ) {
  854. if ( empty( $term->filter ) || 'raw' === $term->filter ) {
  855. $_term = sanitize_term( $term, $taxonomy, 'raw' );
  856. $_term = new WP_Term( $_term );
  857. } else {
  858. $_term = WP_Term::get_instance( $term->term_id );
  859. }
  860. } else {
  861. $_term = WP_Term::get_instance( $term, $taxonomy );
  862. }
  863. if ( is_wp_error( $_term ) ) {
  864. return $_term;
  865. } elseif ( ! $_term ) {
  866. return null;
  867. }
  868. // Ensure for filters that this is not empty.
  869. $taxonomy = $_term->taxonomy;
  870. /**
  871. * Filters a taxonomy term object.
  872. *
  873. * The {@see 'get_$taxonomy'} hook is also available for targeting a specific
  874. * taxonomy.
  875. *
  876. * @since 2.3.0
  877. * @since 4.4.0 `$_term` is now a `WP_Term` object.
  878. *
  879. * @param WP_Term $_term Term object.
  880. * @param string $taxonomy The taxonomy slug.
  881. */
  882. $_term = apply_filters( 'get_term', $_term, $taxonomy );
  883. /**
  884. * Filters a taxonomy term object.
  885. *
  886. * The dynamic portion of the hook name, `$taxonomy`, refers
  887. * to the slug of the term's taxonomy.
  888. *
  889. * Possible hook names include:
  890. *
  891. * - `get_category`
  892. * - `get_post_tag`
  893. *
  894. * @since 2.3.0
  895. * @since 4.4.0 `$_term` is now a `WP_Term` object.
  896. *
  897. * @param WP_Term $_term Term object.
  898. * @param string $taxonomy The taxonomy slug.
  899. */
  900. $_term = apply_filters( "get_{$taxonomy}", $_term, $taxonomy );
  901. // Bail if a filter callback has changed the type of the `$_term` object.
  902. if ( ! ( $_term instanceof WP_Term ) ) {
  903. return $_term;
  904. }
  905. // Sanitize term, according to the specified filter.
  906. $_term->filter( $filter );
  907. if ( ARRAY_A === $output ) {
  908. return $_term->to_array();
  909. } elseif ( ARRAY_N === $output ) {
  910. return array_values( $_term->to_array() );
  911. }
  912. return $_term;
  913. }
  914. /**
  915. * Gets all term data from database by term field and data.
  916. *
  917. * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
  918. * required.
  919. *
  920. * The default $field is 'id', therefore it is possible to also use null for
  921. * field, but not recommended that you do so.
  922. *
  923. * If $value does not exist, the return value will be false. If $taxonomy exists
  924. * and $field and $value combinations exist, the term will be returned.
  925. *
  926. * This function will always return the first term that matches the `$field`-
  927. * `$value`-`$taxonomy` combination specified in the parameters. If your query
  928. * is likely to match more than one term (as is likely to be the case when
  929. * `$field` is 'name', for example), consider using get_terms() instead; that
  930. * way, you will get all matching terms, and can provide your own logic for
  931. * deciding which one was intended.
  932. *
  933. * @todo Better formatting for DocBlock.
  934. *
  935. * @since 2.3.0
  936. * @since 4.4.0 `$taxonomy` is optional if `$field` is 'term_taxonomy_id'. Converted to return
  937. * a WP_Term object if `$output` is `OBJECT`.
  938. * @since 5.5.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
  939. *
  940. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
  941. *
  942. * @param string $field Either 'slug', 'name', 'term_id' (or 'id', 'ID'), or 'term_taxonomy_id'.
  943. * @param string|int $value Search for this term value.
  944. * @param string $taxonomy Taxonomy name. Optional, if `$field` is 'term_taxonomy_id'.
  945. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  946. * correspond to a WP_Term object, an associative array, or a numeric array,
  947. * respectively. Default OBJECT.
  948. * @param string $filter Optional. How to sanitize term fields. Default 'raw'.
  949. * @return WP_Term|array|false WP_Term instance (or array) on success, depending on the `$output` value.
  950. * False if `$taxonomy` does not exist or `$term` was not found.
  951. */
  952. function get_term_by( $field, $value, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
  953. // 'term_taxonomy_id' lookups don't require taxonomy checks.
  954. if ( 'term_taxonomy_id' !== $field && ! taxonomy_exists( $taxonomy ) ) {
  955. return false;
  956. }
  957. // No need to perform a query for empty 'slug' or 'name'.
  958. if ( 'slug' === $field || 'name' === $field ) {
  959. $value = (string) $value;
  960. if ( 0 === strlen( $value ) ) {
  961. return false;
  962. }
  963. }
  964. if ( 'id' === $field || 'ID' === $field || 'term_id' === $field ) {
  965. $term = get_term( (int) $value, $taxonomy, $output, $filter );
  966. if ( is_wp_error( $term ) || null === $term ) {
  967. $term = false;
  968. }
  969. return $term;
  970. }
  971. $args = array(
  972. 'get' => 'all',
  973. 'number' => 1,
  974. 'taxonomy' => $taxonomy,
  975. 'update_term_meta_cache' => false,
  976. 'orderby' => 'none',
  977. 'suppress_filter' => true,
  978. );
  979. switch ( $field ) {
  980. case 'slug':
  981. $args['slug'] = $value;
  982. break;
  983. case 'name':
  984. $args['name'] = $value;
  985. break;
  986. case 'term_taxonomy_id':
  987. $args['term_taxonomy_id'] = $value;
  988. unset( $args['taxonomy'] );
  989. break;
  990. default:
  991. return false;
  992. }
  993. $terms = get_terms( $args );
  994. if ( is_wp_error( $terms ) || empty( $terms ) ) {
  995. return false;
  996. }
  997. $term = array_shift( $terms );
  998. // In the case of 'term_taxonomy_id', override the provided `$taxonomy` with whatever we find in the DB.
  999. if ( 'term_taxonomy_id' === $field ) {
  1000. $taxonomy = $term->taxonomy;
  1001. }
  1002. return get_term( $term, $taxonomy, $output, $filter );
  1003. }
  1004. /**
  1005. * Merges all term children into a single array of their IDs.
  1006. *
  1007. * This recursive function will merge all of the children of $term into the same
  1008. * array of term IDs. Only useful for taxonomies which are hierarchical.
  1009. *
  1010. * Will return an empty array if $term does not exist in $taxonomy.
  1011. *
  1012. * @since 2.3.0
  1013. *
  1014. * @param int $term_id ID of term to get children.
  1015. * @param string $taxonomy Taxonomy name.
  1016. * @return array|WP_Error List of term IDs. WP_Error returned if `$taxonomy` does not exist.
  1017. */
  1018. function get_term_children( $term_id, $taxonomy ) {
  1019. if ( ! taxonomy_exists( $taxonomy ) ) {
  1020. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  1021. }
  1022. $term_id = (int) $term_id;
  1023. $terms = _get_term_hierarchy( $taxonomy );
  1024. if ( ! isset( $terms[ $term_id ] ) ) {
  1025. return array();
  1026. }
  1027. $children = $terms[ $term_id ];
  1028. foreach ( (array) $terms[ $term_id ] as $child ) {
  1029. if ( $term_id === $child ) {
  1030. continue;
  1031. }
  1032. if ( isset( $terms[ $child ] ) ) {
  1033. $children = array_merge( $children, get_term_children( $child, $taxonomy ) );
  1034. }
  1035. }
  1036. return $children;
  1037. }
  1038. /**
  1039. * Gets sanitized term field.
  1040. *
  1041. * The function is for contextual reasons and for simplicity of usage.
  1042. *
  1043. * @since 2.3.0
  1044. * @since 4.4.0 The `$taxonomy` parameter was made optional. `$term` can also now accept a WP_Term object.
  1045. *
  1046. * @see sanitize_term_field()
  1047. *
  1048. * @param string $field Term field to fetch.
  1049. * @param int|WP_Term $term Term ID or object.
  1050. * @param string $taxonomy Optional. Taxonomy name. Default empty.
  1051. * @param string $context Optional. How to sanitize term fields. Look at sanitize_term_field() for available options.
  1052. * Default 'display'.
  1053. * @return string|int|null|WP_Error Will return an empty string if $term is not an object or if $field is not set in $term.
  1054. */
  1055. function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
  1056. $term = get_term( $term, $taxonomy );
  1057. if ( is_wp_error( $term ) ) {
  1058. return $term;
  1059. }
  1060. if ( ! is_object( $term ) ) {
  1061. return '';
  1062. }
  1063. if ( ! isset( $term->$field ) ) {
  1064. return '';
  1065. }
  1066. return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
  1067. }
  1068. /**
  1069. * Sanitizes term for editing.
  1070. *
  1071. * Return value is sanitize_term() and usage is for sanitizing the term for
  1072. * editing. Function is for contextual and simplicity.
  1073. *
  1074. * @since 2.3.0
  1075. *
  1076. * @param int|object $id Term ID or object.
  1077. * @param string $taxonomy Taxonomy name.
  1078. * @return string|int|null|WP_Error Will return empty string if $term is not an object.
  1079. */
  1080. function get_term_to_edit( $id, $taxonomy ) {
  1081. $term = get_term( $id, $taxonomy );
  1082. if ( is_wp_error( $term ) ) {
  1083. return $term;
  1084. }
  1085. if ( ! is_object( $term ) ) {
  1086. return '';
  1087. }
  1088. return sanitize_term( $term, $taxonomy, 'edit' );
  1089. }
  1090. /**
  1091. * Retrieves the terms in a given taxonomy or list of taxonomies.
  1092. *
  1093. * You can fully inject any customizations to the query before it is sent, as
  1094. * well as control the output with a filter.
  1095. *
  1096. * The return type varies depending on the value passed to `$args['fields']`. See
  1097. * WP_Term_Query::get_terms() for details. In all cases, a `WP_Error` object will
  1098. * be returned if an invalid taxonomy is requested.
  1099. *
  1100. * The {@see 'get_terms'} filter will be called when the cache has the term and will
  1101. * pass the found term along with the array of $taxonomies and array of $args.
  1102. * This filter is also called before the array of terms is passed and will pass
  1103. * the array of terms, along with the $taxonomies and $args.
  1104. *
  1105. * The {@see 'list_terms_exclusions'} filter passes the compiled exclusions along with
  1106. * the $args.
  1107. *
  1108. * The {@see 'get_terms_orderby'} filter passes the `ORDER BY` clause for the query
  1109. * along with the $args array.
  1110. *
  1111. * Prior to 4.5.0, the first parameter of `get_terms()` was a taxonomy or list of taxonomies:
  1112. *
  1113. * $terms = get_terms( 'post_tag', array(
  1114. * 'hide_empty' => false,
  1115. * ) );
  1116. *
  1117. * Since 4.5.0, taxonomies should be passed via the 'taxonomy' argument in the `$args` array:
  1118. *
  1119. * $terms = get_terms( array(
  1120. * 'taxonomy' => 'post_tag',
  1121. * 'hide_empty' => false,
  1122. * ) );
  1123. *
  1124. * @since 2.3.0
  1125. * @since 4.2.0 Introduced 'name' and 'childless' parameters.
  1126. * @since 4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the `orderby` parameter.
  1127. * Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return
  1128. * a list of WP_Term objects.
  1129. * @since 4.5.0 Changed the function signature so that the `$args` array can be provided as the first parameter.
  1130. * Introduced 'meta_key' and 'meta_value' parameters. Introduced the ability to order results by metadata.
  1131. * @since 4.8.0 Introduced 'suppress_filter' parameter.
  1132. *
  1133. * @internal The `$deprecated` parameter is parsed for backward compatibility only.
  1134. *
  1135. * @param array|string $args Optional. Array or string of arguments. See WP_Term_Query::__construct()
  1136. * for information on accepted arguments. Default empty array.
  1137. * @param array|string $deprecated Optional. Argument array, when using the legacy function parameter format.
  1138. * If present, this parameter will be interpreted as `$args`, and the first
  1139. * function parameter will be parsed as a taxonomy or array of taxonomies.
  1140. * Default empty.
  1141. * @return WP_Term[]|int[]|string[]|string|WP_Error Array of terms, a count thereof as a numeric string,
  1142. * or WP_Error if any of the taxonomies do not exist.
  1143. * See the function description for more information.
  1144. */
  1145. function get_terms( $args = array(), $deprecated = '' ) {
  1146. $term_query = new WP_Term_Query();
  1147. $defaults = array(
  1148. 'suppress_filter' => false,
  1149. );
  1150. /*
  1151. * Legacy argument format ($taxonomy, $args) takes precedence.
  1152. *
  1153. * We detect legacy argument format by checking if
  1154. * (a) a second non-empty parameter is passed, or
  1155. * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
  1156. */
  1157. $_args = wp_parse_args( $args );
  1158. $key_intersect = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
  1159. $do_legacy_args = $deprecated || empty( $key_intersect );
  1160. if ( $do_legacy_args ) {
  1161. $taxonomies = (array) $args;
  1162. $args = wp_parse_args( $deprecated, $defaults );
  1163. $args['taxonomy'] = $taxonomies;
  1164. } else {
  1165. $args = wp_parse_args( $args, $defaults );
  1166. if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
  1167. $args['taxonomy'] = (array) $args['taxonomy'];
  1168. }
  1169. }
  1170. if ( ! empty( $args['taxonomy'] ) ) {
  1171. foreach ( $args['taxonomy'] as $taxonomy ) {
  1172. if ( ! taxonomy_exists( $taxonomy ) ) {
  1173. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  1174. }
  1175. }
  1176. }
  1177. // Don't pass suppress_filter to WP_Term_Query.
  1178. $suppress_filter = $args['suppress_filter'];
  1179. unset( $args['suppress_filter'] );
  1180. $terms = $term_query->query( $args );
  1181. // Count queries are not filtered, for legacy reasons.
  1182. if ( ! is_array( $terms ) ) {
  1183. return $terms;
  1184. }
  1185. if ( $suppress_filter ) {
  1186. return $terms;
  1187. }
  1188. /**
  1189. * Filters the found terms.
  1190. *
  1191. * @since 2.3.0
  1192. * @since 4.6.0 Added the `$term_query` parameter.
  1193. *
  1194. * @param array $terms Array of found terms.
  1195. * @param array|null $taxonomies An array of taxonomies if known.
  1196. * @param array $args An array of get_terms() arguments.
  1197. * @param WP_Term_Query $term_query The WP_Term_Query object.
  1198. */
  1199. return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
  1200. }
  1201. /**
  1202. * Adds metadata to a term.
  1203. *
  1204. * @since 4.4.0
  1205. *
  1206. * @param int $term_id Term ID.
  1207. * @param string $meta_key Metadata name.
  1208. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  1209. * @param bool $unique Optional. Whether the same key should not be added.
  1210. * Default false.
  1211. * @return int|false|WP_Error Meta ID on success, false on failure.
  1212. * WP_Error when term_id is ambiguous between taxonomies.
  1213. */
  1214. function add_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
  1215. if ( wp_term_is_shared( $term_id ) ) {
  1216. return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
  1217. }
  1218. return add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
  1219. }
  1220. /**
  1221. * Removes metadata matching criteria from a term.
  1222. *
  1223. * @since 4.4.0
  1224. *
  1225. * @param int $term_id Term ID.
  1226. * @param string $meta_key Metadata name.
  1227. * @param mixed $meta_value Optional. Metadata value. If provided,
  1228. * rows will only be removed that match the value.
  1229. * Must be serializable if non-scalar. Default empty.
  1230. * @return bool True on success, false on failure.
  1231. */
  1232. function delete_term_meta( $term_id, $meta_key, $meta_value = '' ) {
  1233. return delete_metadata( 'term', $term_id, $meta_key, $meta_value );
  1234. }
  1235. /**
  1236. * Retrieves metadata for a term.
  1237. *
  1238. * @since 4.4.0
  1239. *
  1240. * @param int $term_id Term ID.
  1241. * @param string $key Optional. The meta key to retrieve. By default,
  1242. * returns data for all keys. Default empty.
  1243. * @param bool $single Optional. Whether to return a single value.
  1244. * This parameter has no effect if `$key` is not specified.
  1245. * Default false.
  1246. * @return mixed An array of values if `$single` is false.
  1247. * The value of the meta field if `$single` is true.
  1248. * False for an invalid `$term_id` (non-numeric, zero, or negative value).
  1249. * An empty string if a valid but non-existing term ID is passed.
  1250. */
  1251. function get_term_meta( $term_id, $key = '', $single = false ) {
  1252. return get_metadata( 'term', $term_id, $key, $single );
  1253. }
  1254. /**
  1255. * Updates term metadata.
  1256. *
  1257. * Use the `$prev_value` parameter to differentiate between meta fields with the same key and term ID.
  1258. *
  1259. * If the meta field for the term does not exist, it will be added.
  1260. *
  1261. * @since 4.4.0
  1262. *
  1263. * @param int $term_id Term ID.
  1264. * @param string $meta_key Metadata key.
  1265. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  1266. * @param mixed $prev_value Optional. Previous value to check before updating.
  1267. * If specified, only update existing metadata entries with
  1268. * this value. Otherwise, update all entries. Default empty.
  1269. * @return int|bool|WP_Error Meta ID if the key didn't exist. true on successful update,
  1270. * false on failure or if the value passed to the function
  1271. * is the same as the one that is already in the database.
  1272. * WP_Error when term_id is ambiguous between taxonomies.
  1273. */
  1274. function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
  1275. if ( wp_term_is_shared( $term_id ) ) {
  1276. return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
  1277. }
  1278. return update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
  1279. }
  1280. /**
  1281. * Updates metadata cache for list of term IDs.
  1282. *
  1283. * Performs SQL query to retrieve all metadata for the terms matching `$term_ids` and stores them in the cache.
  1284. * Subsequent calls to `get_term_meta()` will not need to query the database.
  1285. *
  1286. * @since 4.4.0
  1287. *
  1288. * @param array $term_ids List of term IDs.
  1289. * @return array|false An array of metadata on success, false if there is nothing to update.
  1290. */
  1291. function update_termmeta_cache( $term_ids ) {
  1292. return update_meta_cache( 'term', $term_ids );
  1293. }
  1294. /**
  1295. * Gets all meta data, including meta IDs, for the given term ID.
  1296. *
  1297. * @since 4.9.0
  1298. *
  1299. * @global wpdb $wpdb WordPress database abstraction object.
  1300. *
  1301. * @param int $term_id Term ID.
  1302. * @return array|false Array with meta data, or false when the meta table is not installed.
  1303. */
  1304. function has_term_meta( $term_id ) {
  1305. $check = wp_check_term_meta_support_prefilter( null );
  1306. if ( null !== $check ) {
  1307. return $check;
  1308. }
  1309. global $wpdb;
  1310. return $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value, meta_id, term_id FROM $wpdb->termmeta WHERE term_id = %d ORDER BY meta_key,meta_id", $term_id ), ARRAY_A );
  1311. }
  1312. /**
  1313. * Registers a meta key for terms.
  1314. *
  1315. * @since 4.9.8
  1316. *
  1317. * @param string $taxonomy Taxonomy to register a meta key for. Pass an empty string
  1318. * to register the meta key across all existing taxonomies.
  1319. * @param string $meta_key The meta key to register.
  1320. * @param array $args Data used to describe the meta key when registered. See
  1321. * {@see register_meta()} for a list of supported arguments.
  1322. * @return bool True if the meta key was successfully registered, false if not.
  1323. */
  1324. function register_term_meta( $taxonomy, $meta_key, array $args ) {
  1325. $args['object_subtype'] = $taxonomy;
  1326. return register_meta( 'term', $meta_key, $args );
  1327. }
  1328. /**
  1329. * Unregisters a meta key for terms.
  1330. *
  1331. * @since 4.9.8
  1332. *
  1333. * @param string $taxonomy Taxonomy the meta key is currently registered for. Pass
  1334. * an empty string if the meta key is registered across all
  1335. * existing taxonomies.
  1336. * @param string $meta_key The meta key to unregister.
  1337. * @return bool True on success, false if the meta key was not previously registered.
  1338. */
  1339. function unregister_term_meta( $taxonomy, $meta_key ) {
  1340. return unregister_meta_key( 'term', $meta_key, $taxonomy );
  1341. }
  1342. /**
  1343. * Determines whether a taxonomy term exists.
  1344. *
  1345. * Formerly is_term(), introduced in 2.3.0.
  1346. *
  1347. * For more information on this and similar theme functions, check out
  1348. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1349. * Conditional Tags} article in the Theme Developer Handbook.
  1350. *
  1351. * @since 3.0.0
  1352. * @since 6.0.0 Converted to use `get_terms()`.
  1353. *
  1354. * @global bool $_wp_suspend_cache_invalidation
  1355. *
  1356. * @param int|string $term The term to check. Accepts term ID, slug, or name.
  1357. * @param string $taxonomy Optional. The taxonomy name to use.
  1358. * @param int $parent Optional. ID of parent term under which to confine the exists search.
  1359. * @return mixed Returns null if the term does not exist.
  1360. * Returns the term ID if no taxonomy is specified and the term ID exists.
  1361. * Returns an array of the term ID and the term taxonomy ID if the taxonomy is specified and the pairing exists.
  1362. * Returns 0 if term ID 0 is passed to the function.
  1363. */
  1364. function term_exists( $term, $taxonomy = '', $parent = null ) {
  1365. global $_wp_suspend_cache_invalidation;
  1366. if ( null === $term ) {
  1367. return null;
  1368. }
  1369. $defaults = array(
  1370. 'get' => 'all',
  1371. 'fields' => 'ids',
  1372. 'number' => 1,
  1373. 'update_term_meta_cache' => false,
  1374. 'order' => 'ASC',
  1375. 'orderby' => 'term_id',
  1376. 'suppress_filter' => true,
  1377. );
  1378. // Ensure that while importing, queries are not cached.
  1379. if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
  1380. // @todo Disable caching once #52710 is merged.
  1381. $defaults['cache_domain'] = microtime();
  1382. }
  1383. if ( ! empty( $taxonomy ) ) {
  1384. $defaults['taxonomy'] = $taxonomy;
  1385. $defaults['fields'] = 'all';
  1386. }
  1387. /**
  1388. * Filters default query arguments for checking if a term exists.
  1389. *
  1390. * @since 6.0.0
  1391. *
  1392. * @param array $defaults An array of arguments passed to get_terms().
  1393. * @param int|string $term The term to check. Accepts term ID, slug, or name.
  1394. * @param string $taxonomy The taxonomy name to use. An empty string indicates
  1395. * the search is against all taxonomies.
  1396. * @param int|null $parent ID of parent term under which to confine the exists search.
  1397. * Null indicates the search is unconfined.
  1398. */
  1399. $defaults = apply_filters( 'term_exists_default_query_args', $defaults, $term, $taxonomy, $parent );
  1400. if ( is_int( $term ) ) {
  1401. if ( 0 === $term ) {
  1402. return 0;
  1403. }
  1404. $args = wp_parse_args( array( 'include' => array( $term ) ), $defaults );
  1405. $terms = get_terms( $args );
  1406. } else {
  1407. $term = trim( wp_unslash( $term ) );
  1408. if ( '' === $term ) {
  1409. return null;
  1410. }
  1411. if ( ! empty( $taxonomy ) && is_numeric( $parent ) ) {
  1412. $defaults['parent'] = (int) $parent;
  1413. }
  1414. $args = wp_parse_args( array( 'slug' => sanitize_title( $term ) ), $defaults );
  1415. $terms = get_terms( $args );
  1416. if ( empty( $terms ) || is_wp_error( $terms ) ) {
  1417. $args = wp_parse_args( array( 'name' => $term ), $defaults );
  1418. $terms = get_terms( $args );
  1419. }
  1420. }
  1421. if ( empty( $terms ) || is_wp_error( $terms ) ) {
  1422. return null;
  1423. }
  1424. $_term = array_shift( $terms );
  1425. if ( ! empty( $taxonomy ) ) {
  1426. return array(
  1427. 'term_id' => (string) $_term->term_id,
  1428. 'term_taxonomy_id' => (string) $_term->term_taxonomy_id,
  1429. );
  1430. }
  1431. return (string) $_term;
  1432. }
  1433. /**
  1434. * Checks if a term is an ancestor of another term.
  1435. *
  1436. * You can use either an ID or the term object for both parameters.
  1437. *
  1438. * @since 3.4.0
  1439. *
  1440. * @param int|object $term1 ID or object to check if this is the parent term.
  1441. * @param int|object $term2 The child term.
  1442. * @param string $taxonomy Taxonomy name that $term1 and `$term2` belong to.
  1443. * @return bool Whether `$term2` is a child of `$term1`.
  1444. */
  1445. function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
  1446. if ( ! isset( $term1->term_id ) ) {
  1447. $term1 = get_term( $term1, $taxonomy );
  1448. }
  1449. if ( ! isset( $term2->parent ) ) {
  1450. $term2 = get_term( $term2, $taxonomy );
  1451. }
  1452. if ( empty( $term1->term_id ) || empty( $term2->parent ) ) {
  1453. return false;
  1454. }
  1455. if ( $term2->parent === $term1->term_id ) {
  1456. return true;
  1457. }
  1458. return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
  1459. }
  1460. /**
  1461. * Sanitizes all term fields.
  1462. *
  1463. * Relies on sanitize_term_field() to sanitize the term. The difference is that
  1464. * this function will sanitize **all** fields. The context is based
  1465. * on sanitize_term_field().
  1466. *
  1467. * The `$term` is expected to be either an array or an object.
  1468. *
  1469. * @since 2.3.0
  1470. *
  1471. * @param array|object $term The term to check.
  1472. * @param string $taxonomy The taxonomy name to use.
  1473. * @param string $context Optional. Context in which to sanitize the term.
  1474. * Accepts 'raw', 'edit', 'db', 'display', 'rss',
  1475. * 'attribute', or 'js'. Default 'display'.
  1476. * @return array|object Term with all fields sanitized.
  1477. */
  1478. function sanitize_term( $term, $taxonomy, $context = 'display' ) {
  1479. $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
  1480. $do_object = is_object( $term );
  1481. $term_id = $do_object ? $term->term_id : ( isset( $term['term_id'] ) ? $term['term_id'] : 0 );
  1482. foreach ( (array) $fields as $field ) {
  1483. if ( $do_object ) {
  1484. if ( isset( $term->$field ) ) {
  1485. $term->$field = sanitize_term_field( $field, $term->$field, $term_id, $taxonomy, $context );
  1486. }
  1487. } else {
  1488. if ( isset( $term[ $field ] ) ) {
  1489. $term[ $field ] = sanitize_term_field( $field, $term[ $field ], $term_id, $taxonomy, $context );
  1490. }
  1491. }
  1492. }
  1493. if ( $do_object ) {
  1494. $term->filter = $context;
  1495. } else {
  1496. $term['filter'] = $context;
  1497. }
  1498. return $term;
  1499. }
  1500. /**
  1501. * Sanitizes the field value in the term based on the context.
  1502. *
  1503. * Passing a term field value through the function should be assumed to have
  1504. * cleansed the value for whatever context the term field is going to be used.
  1505. *
  1506. * If no context or an unsupported context is given, then default filters will
  1507. * be applied.
  1508. *
  1509. * There are enough filters for each context to support a custom filtering
  1510. * without creating your own filter function. Simply create a function that
  1511. * hooks into the filter you need.
  1512. *
  1513. * @since 2.3.0
  1514. *
  1515. * @param string $field Term field to sanitize.
  1516. * @param string $value Search for this term value.
  1517. * @param int $term_id Term ID.
  1518. * @param string $taxonomy Taxonomy name.
  1519. * @param string $context Context in which to sanitize the term field.
  1520. * Accepts 'raw', 'edit', 'db', 'display', 'rss',
  1521. * 'attribute', or 'js'. Default 'display'.
  1522. * @return mixed Sanitized field.
  1523. */
  1524. function sanitize_term_field( $field, $value, $term_id, $taxonomy, $context ) {
  1525. $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
  1526. if ( in_array( $field, $int_fields, true ) ) {
  1527. $value = (int) $value;
  1528. if ( $value < 0 ) {
  1529. $value = 0;
  1530. }
  1531. }
  1532. $context = strtolower( $context );
  1533. if ( 'raw' === $context ) {
  1534. return $value;
  1535. }
  1536. if ( 'edit' === $context ) {
  1537. /**
  1538. * Filters a term field to edit before it is sanitized.
  1539. *
  1540. * The dynamic portion of the hook name, `$field`, refers to the term field.
  1541. *
  1542. * @since 2.3.0
  1543. *
  1544. * @param mixed $value Value of the term field.
  1545. * @param int $term_id Term ID.
  1546. * @param string $taxonomy Taxonomy slug.
  1547. */
  1548. $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
  1549. /**
  1550. * Filters the taxonomy field to edit before it is sanitized.
  1551. *
  1552. * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
  1553. * to the taxonomy slug and taxonomy field, respectively.
  1554. *
  1555. * @since 2.3.0
  1556. *
  1557. * @param mixed $value Value of the taxonomy field to edit.
  1558. * @param int $term_id Term ID.
  1559. */
  1560. $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
  1561. if ( 'description' === $field ) {
  1562. $value = esc_html( $value ); // textarea_escaped
  1563. } else {
  1564. $value = esc_attr( $value );
  1565. }
  1566. } elseif ( 'db' === $context ) {
  1567. /**
  1568. * Filters a term field value before it is sanitized.
  1569. *
  1570. * The dynamic portion of the hook name, `$field`, refers to the term field.
  1571. *
  1572. * @since 2.3.0
  1573. *
  1574. * @param mixed $value Value of the term field.
  1575. * @param string $taxonomy Taxonomy slug.
  1576. */
  1577. $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
  1578. /**
  1579. * Filters a taxonomy field before it is sanitized.
  1580. *
  1581. * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
  1582. * to the taxonomy slug and field name, respectively.
  1583. *
  1584. * @since 2.3.0
  1585. *
  1586. * @param mixed $value Value of the taxonomy field.
  1587. */
  1588. $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
  1589. // Back compat filters.
  1590. if ( 'slug' === $field ) {
  1591. /**
  1592. * Filters the category nicename before it is sanitized.
  1593. *
  1594. * Use the {@see 'pre_$taxonomy_$field'} hook instead.
  1595. *
  1596. * @since 2.0.3
  1597. *
  1598. * @param string $value The category nicename.
  1599. */
  1600. $value = apply_filters( 'pre_category_nicename', $value );
  1601. }
  1602. } elseif ( 'rss' === $context ) {
  1603. /**
  1604. * Filters the term field for use in RSS.
  1605. *
  1606. * The dynamic portion of the hook name, `$field`, refers to the term field.
  1607. *
  1608. * @since 2.3.0
  1609. *
  1610. * @param mixed $value Value of the term field.
  1611. * @param string $taxonomy Taxonomy slug.
  1612. */
  1613. $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
  1614. /**
  1615. * Filters the taxonomy field for use in RSS.
  1616. *
  1617. * The dynamic portions of the hook name, `$taxonomy`, and `$field`, refer
  1618. * to the taxonomy slug and field name, respectively.
  1619. *
  1620. * @since 2.3.0
  1621. *
  1622. * @param mixed $value Value of the taxonomy field.
  1623. */
  1624. $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
  1625. } else {
  1626. // Use display filters by default.
  1627. /**
  1628. * Filters the term field sanitized for display.
  1629. *
  1630. * The dynamic portion of the hook name, `$field`, refers to the term field name.
  1631. *
  1632. * @since 2.3.0
  1633. *
  1634. * @param mixed $value Value of the term field.
  1635. * @param int $term_id Term ID.
  1636. * @param string $taxonomy Taxonomy slug.
  1637. * @param string $context Context to retrieve the term field value.
  1638. */
  1639. $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
  1640. /**
  1641. * Filters the taxonomy field sanitized for display.
  1642. *
  1643. * The dynamic portions of the filter name, `$taxonomy`, and `$field`, refer
  1644. * to the taxonomy slug and taxonomy field, respectively.
  1645. *
  1646. * @since 2.3.0
  1647. *
  1648. * @param mixed $value Value of the taxonomy field.
  1649. * @param int $term_id Term ID.
  1650. * @param string $context Context to retrieve the taxonomy field value.
  1651. */
  1652. $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
  1653. }
  1654. if ( 'attribute' === $context ) {
  1655. $value = esc_attr( $value );
  1656. } elseif ( 'js' === $context ) {
  1657. $value = esc_js( $value );
  1658. }
  1659. // Restore the type for integer fields after esc_attr().
  1660. if ( in_array( $field, $int_fields, true ) ) {
  1661. $value = (int) $value;
  1662. }
  1663. return $value;
  1664. }
  1665. /**
  1666. * Counts how many terms are in taxonomy.
  1667. *
  1668. * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
  1669. *
  1670. * @since 2.3.0
  1671. * @since 5.6.0 Changed the function signature so that the `$args` array can be provided as the first parameter.
  1672. *
  1673. * @internal The `$deprecated` parameter is parsed for backward compatibility only.
  1674. *
  1675. * @param array|string $args Optional. Array or string of arguments. See WP_Term_Query::__construct()
  1676. * for information on accepted arguments. Default empty array.
  1677. * @param array|string $deprecated Optional. Argument array, when using the legacy function parameter format.
  1678. * If present, this parameter will be interpreted as `$args`, and the first
  1679. * function parameter will be parsed as a taxonomy or array of taxonomies.
  1680. * Default empty.
  1681. * @return string|WP_Error Numeric string containing the number of terms in that
  1682. * taxonomy or WP_Error if the taxonomy does not exist.
  1683. */
  1684. function wp_count_terms( $args = array(), $deprecated = '' ) {
  1685. $use_legacy_args = false;
  1686. // Check whether function is used with legacy signature: `$taxonomy` and `$args`.
  1687. if ( $args
  1688. && ( is_string( $args ) && taxonomy_exists( $args )
  1689. || is_array( $args ) && wp_is_numeric_array( $args ) )
  1690. ) {
  1691. $use_legacy_args = true;
  1692. }
  1693. $defaults = array( 'hide_empty' => false );
  1694. if ( $use_legacy_args ) {
  1695. $defaults['taxonomy'] = $args;
  1696. $args = $deprecated;
  1697. }
  1698. $args = wp_parse_args( $args, $defaults );
  1699. // Backward compatibility.
  1700. if ( isset( $args['ignore_empty'] ) ) {
  1701. $args['hide_empty'] = $args['ignore_empty'];
  1702. unset( $args['ignore_empty'] );
  1703. }
  1704. $args['fields'] = 'count';
  1705. return get_terms( $args );
  1706. }
  1707. /**
  1708. * Unlinks the object from the taxonomy or taxonomies.
  1709. *
  1710. * Will remove all relationships between the object and any terms in
  1711. * a particular taxonomy or taxonomies. Does not remove the term or
  1712. * taxonomy itself.
  1713. *
  1714. * @since 2.3.0
  1715. *
  1716. * @param int $object_id The term object ID that refers to the term.
  1717. * @param string|array $taxonomies List of taxonomy names or single taxonomy name.
  1718. */
  1719. function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
  1720. $object_id = (int) $object_id;
  1721. if ( ! is_array( $taxonomies ) ) {
  1722. $taxonomies = array( $taxonomies );
  1723. }
  1724. foreach ( (array) $taxonomies as $taxonomy ) {
  1725. $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
  1726. $term_ids = array_map( 'intval', $term_ids );
  1727. wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
  1728. }
  1729. }
  1730. /**
  1731. * Removes a term from the database.
  1732. *
  1733. * If the term is a parent of other terms, then the children will be updated to
  1734. * that term's parent.
  1735. *
  1736. * Metadata associated with the term will be deleted.
  1737. *
  1738. * @since 2.3.0
  1739. *
  1740. * @global wpdb $wpdb WordPress database abstraction object.
  1741. *
  1742. * @param int $term Term ID.
  1743. * @param string $taxonomy Taxonomy name.
  1744. * @param array|string $args {
  1745. * Optional. Array of arguments to override the default term ID. Default empty array.
  1746. *
  1747. * @type int $default The term ID to make the default term. This will only override
  1748. * the terms found if there is only one term found. Any other and
  1749. * the found terms are used.
  1750. * @type bool $force_default Optional. Whether to force the supplied term as default to be
  1751. * assigned even if the object was not going to be term-less.
  1752. * Default false.
  1753. * }
  1754. * @return bool|int|WP_Error True on success, false if term does not exist. Zero on attempted
  1755. * deletion of default Category. WP_Error if the taxonomy does not exist.
  1756. */
  1757. function wp_delete_term( $term, $taxonomy, $args = array() ) {
  1758. global $wpdb;
  1759. $term = (int) $term;
  1760. $ids = term_exists( $term, $taxonomy );
  1761. if ( ! $ids ) {
  1762. return false;
  1763. }
  1764. if ( is_wp_error( $ids ) ) {
  1765. return $ids;
  1766. }
  1767. $tt_id = $ids['term_taxonomy_id'];
  1768. $defaults = array();
  1769. if ( 'category' === $taxonomy ) {
  1770. $defaults['default'] = (int) get_option( 'default_category' );
  1771. if ( $defaults['default'] === $term ) {
  1772. return 0; // Don't delete the default category.
  1773. }
  1774. }
  1775. // Don't delete the default custom taxonomy term.
  1776. $taxonomy_object = get_taxonomy( $taxonomy );
  1777. if ( ! empty( $taxonomy_object->default_term ) ) {
  1778. $defaults['default'] = (int) get_option( 'default_term_' . $taxonomy );
  1779. if ( $defaults['default'] === $term ) {
  1780. return 0;
  1781. }
  1782. }
  1783. $args = wp_parse_args( $args, $defaults );
  1784. if ( isset( $args['default'] ) ) {
  1785. $default = (int) $args['default'];
  1786. if ( ! term_exists( $default, $taxonomy ) ) {
  1787. unset( $default );
  1788. }
  1789. }
  1790. if ( isset( $args['force_default'] ) ) {
  1791. $force_default = $args['force_default'];
  1792. }
  1793. /**
  1794. * Fires when deleting a term, before any modifications are made to posts or terms.
  1795. *
  1796. * @since 4.1.0
  1797. *
  1798. * @param int $term Term ID.
  1799. * @param string $taxonomy Taxonomy name.
  1800. */
  1801. do_action( 'pre_delete_term', $term, $taxonomy );
  1802. // Update children to point to new parent.
  1803. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  1804. $term_obj = get_term( $term, $taxonomy );
  1805. if ( is_wp_error( $term_obj ) ) {
  1806. return $term_obj;
  1807. }
  1808. $parent = $term_obj->parent;
  1809. $edit_ids = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int) $term_obj->term_id );
  1810. $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
  1811. /**
  1812. * Fires immediately before a term to delete's children are reassigned a parent.
  1813. *
  1814. * @since 2.9.0
  1815. *
  1816. * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
  1817. */
  1818. do_action( 'edit_term_taxonomies', $edit_tt_ids );
  1819. $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id ) + compact( 'taxonomy' ) );
  1820. // Clean the cache for all child terms.
  1821. $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
  1822. clean_term_cache( $edit_term_ids, $taxonomy );
  1823. /**
  1824. * Fires immediately after a term to delete's children are reassigned a parent.
  1825. *
  1826. * @since 2.9.0
  1827. *
  1828. * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
  1829. */
  1830. do_action( 'edited_term_taxonomies', $edit_tt_ids );
  1831. }
  1832. // Get the term before deleting it or its term relationships so we can pass to actions below.
  1833. $deleted_term = get_term( $term, $taxonomy );
  1834. $object_ids = (array) $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
  1835. foreach ( $object_ids as $object_id ) {
  1836. if ( ! isset( $default ) ) {
  1837. wp_remove_object_terms( $object_id, $term, $taxonomy );
  1838. continue;
  1839. }
  1840. $terms = wp_get_object_terms(
  1841. $object_id,
  1842. $taxonomy,
  1843. array(
  1844. 'fields' => 'ids',
  1845. 'orderby' => 'none',
  1846. )
  1847. );
  1848. if ( 1 === count( $terms ) && isset( $default ) ) {
  1849. $terms = array( $default );
  1850. } else {
  1851. $terms = array_diff( $terms, array( $term ) );
  1852. if ( isset( $default ) && isset( $force_default ) && $force_default ) {
  1853. $terms = array_merge( $terms, array( $default ) );
  1854. }
  1855. }
  1856. $terms = array_map( 'intval', $terms );
  1857. wp_set_object_terms( $object_id, $terms, $taxonomy );
  1858. }
  1859. // Clean the relationship caches for all object types using this term.
  1860. $tax_object = get_taxonomy( $taxonomy );
  1861. foreach ( $tax_object->object_type as $object_type ) {
  1862. clean_object_term_cache( $object_ids, $object_type );
  1863. }
  1864. $term_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->termmeta WHERE term_id = %d ", $term ) );
  1865. foreach ( $term_meta_ids as $mid ) {
  1866. delete_metadata_by_mid( 'term', $mid );
  1867. }
  1868. /**
  1869. * Fires immediately before a term taxonomy ID is deleted.
  1870. *
  1871. * @since 2.9.0
  1872. *
  1873. * @param int $tt_id Term taxonomy ID.
  1874. */
  1875. do_action( 'delete_term_taxonomy', $tt_id );
  1876. $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
  1877. /**
  1878. * Fires immediately after a term taxonomy ID is deleted.
  1879. *
  1880. * @since 2.9.0
  1881. *
  1882. * @param int $tt_id Term taxonomy ID.
  1883. */
  1884. do_action( 'deleted_term_taxonomy', $tt_id );
  1885. // Delete the term if no taxonomies use it.
  1886. if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term ) ) ) {
  1887. $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
  1888. }
  1889. clean_term_cache( $term, $taxonomy );
  1890. /**
  1891. * Fires after a term is deleted from the database and the cache is cleaned.
  1892. *
  1893. * The {@see 'delete_$taxonomy'} hook is also available for targeting a specific
  1894. * taxonomy.
  1895. *
  1896. * @since 2.5.0
  1897. * @since 4.5.0 Introduced the `$object_ids` argument.
  1898. *
  1899. * @param int $term Term ID.
  1900. * @param int $tt_id Term taxonomy ID.
  1901. * @param string $taxonomy Taxonomy slug.
  1902. * @param WP_Term $deleted_term Copy of the already-deleted term.
  1903. * @param array $object_ids List of term object IDs.
  1904. */
  1905. do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term, $object_ids );
  1906. /**
  1907. * Fires after a term in a specific taxonomy is deleted.
  1908. *
  1909. * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
  1910. * taxonomy the term belonged to.
  1911. *
  1912. * Possible hook names include:
  1913. *
  1914. * - `delete_category`
  1915. * - `delete_post_tag`
  1916. *
  1917. * @since 2.3.0
  1918. * @since 4.5.0 Introduced the `$object_ids` argument.
  1919. *
  1920. * @param int $term Term ID.
  1921. * @param int $tt_id Term taxonomy ID.
  1922. * @param WP_Term $deleted_term Copy of the already-deleted term.
  1923. * @param array $object_ids List of term object IDs.
  1924. */
  1925. do_action( "delete_{$taxonomy}", $term, $tt_id, $deleted_term, $object_ids );
  1926. return true;
  1927. }
  1928. /**
  1929. * Deletes one existing category.
  1930. *
  1931. * @since 2.0.0
  1932. *
  1933. * @param int $cat_ID Category term ID.
  1934. * @return bool|int|WP_Error Returns true if completes delete action; false if term doesn't exist;
  1935. * Zero on attempted deletion of default Category; WP_Error object is
  1936. * also a possibility.
  1937. */
  1938. function wp_delete_category( $cat_ID ) {
  1939. return wp_delete_term( $cat_ID, 'category' );
  1940. }
  1941. /**
  1942. * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
  1943. *
  1944. * @since 2.3.0
  1945. * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
  1946. * Introduced `$parent` argument.
  1947. * @since 4.4.0 Introduced `$meta_query` and `$update_term_meta_cache` arguments. When `$fields` is 'all' or
  1948. * 'all_with_object_id', an array of `WP_Term` objects will be returned.
  1949. * @since 4.7.0 Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments.
  1950. *
  1951. * @param int|int[] $object_ids The ID(s) of the object(s) to retrieve.
  1952. * @param string|string[] $taxonomies The taxonomy names to retrieve terms from.
  1953. * @param array|string $args See WP_Term_Query::__construct() for supported arguments.
  1954. * @return WP_Term[]|int[]|string[]|string|WP_Error Array of terms, a count thereof as a numeric string,
  1955. * or WP_Error if any of the taxonomies do not exist.
  1956. * See WP_Term_Query::get_terms() for more information.
  1957. */
  1958. function wp_get_object_terms( $object_ids, $taxonomies, $args = array() ) {
  1959. if ( empty( $object_ids ) || empty( $taxonomies ) ) {
  1960. return array();
  1961. }
  1962. if ( ! is_array( $taxonomies ) ) {
  1963. $taxonomies = array( $taxonomies );
  1964. }
  1965. foreach ( $taxonomies as $taxonomy ) {
  1966. if ( ! taxonomy_exists( $taxonomy ) ) {
  1967. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  1968. }
  1969. }
  1970. if ( ! is_array( $object_ids ) ) {
  1971. $object_ids = array( $object_ids );
  1972. }
  1973. $object_ids = array_map( 'intval', $object_ids );
  1974. $args = wp_parse_args( $args );
  1975. /**
  1976. * Filters arguments for retrieving object terms.
  1977. *
  1978. * @since 4.9.0
  1979. *
  1980. * @param array $args An array of arguments for retrieving terms for the given object(s).
  1981. * See {@see wp_get_object_terms()} for details.
  1982. * @param int[] $object_ids Array of object IDs.
  1983. * @param string[] $taxonomies Array of taxonomy names to retrieve terms from.
  1984. */
  1985. $args = apply_filters( 'wp_get_object_terms_args', $args, $object_ids, $taxonomies );
  1986. /*
  1987. * When one or more queried taxonomies is registered with an 'args' array,
  1988. * those params override the `$args` passed to this function.
  1989. */
  1990. $terms = array();
  1991. if ( count( $taxonomies ) > 1 ) {
  1992. foreach ( $taxonomies as $index => $taxonomy ) {
  1993. $t = get_taxonomy( $taxonomy );
  1994. if ( isset( $t->args ) && is_array( $t->args ) && array_merge( $args, $t->args ) != $args ) {
  1995. unset( $taxonomies[ $index ] );
  1996. $terms = array_merge( $terms, wp_get_object_terms( $object_ids, $taxonomy, array_merge( $args, $t->args ) ) );
  1997. }
  1998. }
  1999. } else {
  2000. $t = get_taxonomy( $taxonomies[0] );
  2001. if ( isset( $t->args ) && is_array( $t->args ) ) {
  2002. $args = array_merge( $args, $t->args );
  2003. }
  2004. }
  2005. $args['taxonomy'] = $taxonomies;
  2006. $args['object_ids'] = $object_ids;
  2007. // Taxonomies registered without an 'args' param are handled here.
  2008. if ( ! empty( $taxonomies ) ) {
  2009. $terms_from_remaining_taxonomies = get_terms( $args );
  2010. // Array keys should be preserved for values of $fields that use term_id for keys.
  2011. if ( ! empty( $args['fields'] ) && 0 === strpos( $args['fields'], 'id=>' ) ) {
  2012. $terms = $terms + $terms_from_remaining_taxonomies;
  2013. } else {
  2014. $terms = array_merge( $terms, $terms_from_remaining_taxonomies );
  2015. }
  2016. }
  2017. /**
  2018. * Filters the terms for a given object or objects.
  2019. *
  2020. * @since 4.2.0
  2021. *
  2022. * @param WP_Term[]|int[]|string[]|string $terms Array of terms or a count thereof as a numeric string.
  2023. * @param int[] $object_ids Array of object IDs for which terms were retrieved.
  2024. * @param string[] $taxonomies Array of taxonomy names from which terms were retrieved.
  2025. * @param array $args Array of arguments for retrieving terms for the given
  2026. * object(s). See wp_get_object_terms() for details.
  2027. */
  2028. $terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );
  2029. $object_ids = implode( ',', $object_ids );
  2030. $taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
  2031. /**
  2032. * Filters the terms for a given object or objects.
  2033. *
  2034. * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
  2035. * {@see 'get_object_terms'} filter is recommended as an alternative.
  2036. *
  2037. * @since 2.8.0
  2038. *
  2039. * @param WP_Term[]|int[]|string[]|string $terms Array of terms or a count thereof as a numeric string.
  2040. * @param string $object_ids Comma separated list of object IDs for which terms were retrieved.
  2041. * @param string $taxonomies SQL fragment of taxonomy names from which terms were retrieved.
  2042. * @param array $args Array of arguments for retrieving terms for the given
  2043. * object(s). See wp_get_object_terms() for details.
  2044. */
  2045. return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
  2046. }
  2047. /**
  2048. * Adds a new term to the database.
  2049. *
  2050. * A non-existent term is inserted in the following sequence:
  2051. * 1. The term is added to the term table, then related to the taxonomy.
  2052. * 2. If everything is correct, several actions are fired.
  2053. * 3. The 'term_id_filter' is evaluated.
  2054. * 4. The term cache is cleaned.
  2055. * 5. Several more actions are fired.
  2056. * 6. An array is returned containing the `term_id` and `term_taxonomy_id`.
  2057. *
  2058. * If the 'slug' argument is not empty, then it is checked to see if the term
  2059. * is invalid. If it is not a valid, existing term, it is added and the term_id
  2060. * is given.
  2061. *
  2062. * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
  2063. * the term is inserted and the term_id will be given.
  2064. *
  2065. * Error handling:
  2066. * If `$taxonomy` does not exist or `$term` is empty,
  2067. * a WP_Error object will be returned.
  2068. *
  2069. * If the term already exists on the same hierarchical level,
  2070. * or the term slug and name are not unique, a WP_Error object will be returned.
  2071. *
  2072. * @global wpdb $wpdb WordPress database abstraction object.
  2073. *
  2074. * @since 2.3.0
  2075. *
  2076. * @param string $term The term name to add.
  2077. * @param string $taxonomy The taxonomy to which to add the term.
  2078. * @param array|string $args {
  2079. * Optional. Array or query string of arguments for inserting a term.
  2080. *
  2081. * @type string $alias_of Slug of the term to make this term an alias of.
  2082. * Default empty string. Accepts a term slug.
  2083. * @type string $description The term description. Default empty string.
  2084. * @type int $parent The id of the parent term. Default 0.
  2085. * @type string $slug The term slug to use. Default empty string.
  2086. * }
  2087. * @return array|WP_Error {
  2088. * An array of the new term data, WP_Error otherwise.
  2089. *
  2090. * @type int $term_id The new term ID.
  2091. * @type int|string $term_taxonomy_id The new term taxonomy ID. Can be a numeric string.
  2092. * }
  2093. */
  2094. function wp_insert_term( $term, $taxonomy, $args = array() ) {
  2095. global $wpdb;
  2096. if ( ! taxonomy_exists( $taxonomy ) ) {
  2097. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  2098. }
  2099. /**
  2100. * Filters a term before it is sanitized and inserted into the database.
  2101. *
  2102. * @since 3.0.0
  2103. * @since 6.1.0 The `$args` parameter was added.
  2104. *
  2105. * @param string|WP_Error $term The term name to add, or a WP_Error object if there's an error.
  2106. * @param string $taxonomy Taxonomy slug.
  2107. * @param array|string $args Array or query string of arguments passed to wp_insert_term().
  2108. */
  2109. $term = apply_filters( 'pre_insert_term', $term, $taxonomy, $args );
  2110. if ( is_wp_error( $term ) ) {
  2111. return $term;
  2112. }
  2113. if ( is_int( $term ) && 0 === $term ) {
  2114. return new WP_Error( 'invalid_term_id', __( 'Invalid term ID.' ) );
  2115. }
  2116. if ( '' === trim( $term ) ) {
  2117. return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
  2118. }
  2119. $defaults = array(
  2120. 'alias_of' => '',
  2121. 'description' => '',
  2122. 'parent' => 0,
  2123. 'slug' => '',
  2124. );
  2125. $args = wp_parse_args( $args, $defaults );
  2126. if ( (int) $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
  2127. return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
  2128. }
  2129. $args['name'] = $term;
  2130. $args['taxonomy'] = $taxonomy;
  2131. // Coerce null description to strings, to avoid database errors.
  2132. $args['description'] = (string) $args['description'];
  2133. $args = sanitize_term( $args, $taxonomy, 'db' );
  2134. // expected_slashed ($name)
  2135. $name = wp_unslash( $args['name'] );
  2136. $description = wp_unslash( $args['description'] );
  2137. $parent = (int) $args['parent'];
  2138. $slug_provided = ! empty( $args['slug'] );
  2139. if ( ! $slug_provided ) {
  2140. $slug = sanitize_title( $name );
  2141. } else {
  2142. $slug = $args['slug'];
  2143. }
  2144. $term_group = 0;
  2145. if ( $args['alias_of'] ) {
  2146. $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
  2147. if ( ! empty( $alias->term_group ) ) {
  2148. // The alias we want is already in a group, so let's use that one.
  2149. $term_group = $alias->term_group;
  2150. } elseif ( ! empty( $alias->term_id ) ) {
  2151. /*
  2152. * The alias is not in a group, so we create a new one
  2153. * and add the alias to it.
  2154. */
  2155. $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1;
  2156. wp_update_term(
  2157. $alias->term_id,
  2158. $taxonomy,
  2159. array(
  2160. 'term_group' => $term_group,
  2161. )
  2162. );
  2163. }
  2164. }
  2165. /*
  2166. * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
  2167. * unless a unique slug has been explicitly provided.
  2168. */
  2169. $name_matches = get_terms(
  2170. array(
  2171. 'taxonomy' => $taxonomy,
  2172. 'name' => $name,
  2173. 'hide_empty' => false,
  2174. 'parent' => $args['parent'],
  2175. 'update_term_meta_cache' => false,
  2176. )
  2177. );
  2178. /*
  2179. * The `name` match in `get_terms()` doesn't differentiate accented characters,
  2180. * so we do a stricter comparison here.
  2181. */
  2182. $name_match = null;
  2183. if ( $name_matches ) {
  2184. foreach ( $name_matches as $_match ) {
  2185. if ( strtolower( $name ) === strtolower( $_match->name ) ) {
  2186. $name_match = $_match;
  2187. break;
  2188. }
  2189. }
  2190. }
  2191. if ( $name_match ) {
  2192. $slug_match = get_term_by( 'slug', $slug, $taxonomy );
  2193. if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
  2194. if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  2195. $siblings = get_terms(
  2196. array(
  2197. 'taxonomy' => $taxonomy,
  2198. 'get' => 'all',
  2199. 'parent' => $parent,
  2200. 'update_term_meta_cache' => false,
  2201. )
  2202. );
  2203. $existing_term = null;
  2204. $sibling_names = wp_list_pluck( $siblings, 'name' );
  2205. $sibling_slugs = wp_list_pluck( $siblings, 'slug' );
  2206. if ( ( ! $slug_provided || $name_match->slug === $slug ) && in_array( $name, $sibling_names, true ) ) {
  2207. $existing_term = $name_match;
  2208. } elseif ( $slug_match && in_array( $slug, $sibling_slugs, true ) ) {
  2209. $existing_term = $slug_match;
  2210. }
  2211. if ( $existing_term ) {
  2212. return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
  2213. }
  2214. } else {
  2215. return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id );
  2216. }
  2217. }
  2218. }
  2219. $slug = wp_unique_term_slug( $slug, (object) $args );
  2220. $data = compact( 'name', 'slug', 'term_group' );
  2221. /**
  2222. * Filters term data before it is inserted into the database.
  2223. *
  2224. * @since 4.7.0
  2225. *
  2226. * @param array $data Term data to be inserted.
  2227. * @param string $taxonomy Taxonomy slug.
  2228. * @param array $args Arguments passed to wp_insert_term().
  2229. */
  2230. $data = apply_filters( 'wp_insert_term_data', $data, $taxonomy, $args );
  2231. if ( false === $wpdb->insert( $wpdb->terms, $data ) ) {
  2232. return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database.' ), $wpdb->last_error );
  2233. }
  2234. $term_id = (int) $wpdb->insert_id;
  2235. // Seems unreachable. However, is used in the case that a term name is provided, which sanitizes to an empty string.
  2236. if ( empty( $slug ) ) {
  2237. $slug = sanitize_title( $slug, $term_id );
  2238. /** This action is documented in wp-includes/taxonomy.php */
  2239. do_action( 'edit_terms', $term_id, $taxonomy );
  2240. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2241. /** This action is documented in wp-includes/taxonomy.php */
  2242. do_action( 'edited_terms', $term_id, $taxonomy );
  2243. }
  2244. $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
  2245. if ( ! empty( $tt_id ) ) {
  2246. return array(
  2247. 'term_id' => $term_id,
  2248. 'term_taxonomy_id' => $tt_id,
  2249. );
  2250. }
  2251. if ( false === $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ) + array( 'count' => 0 ) ) ) {
  2252. return new WP_Error( 'db_insert_error', __( 'Could not insert term taxonomy into the database.' ), $wpdb->last_error );
  2253. }
  2254. $tt_id = (int) $wpdb->insert_id;
  2255. /*
  2256. * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
  2257. * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
  2258. * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
  2259. * are not fired.
  2260. */
  2261. $duplicate_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.term_id, t.slug, tt.term_taxonomy_id, tt.taxonomy FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON ( tt.term_id = t.term_id ) WHERE t.slug = %s AND tt.parent = %d AND tt.taxonomy = %s AND t.term_id < %d AND tt.term_taxonomy_id != %d", $slug, $parent, $taxonomy, $term_id, $tt_id ) );
  2262. /**
  2263. * Filters the duplicate term check that takes place during term creation.
  2264. *
  2265. * Term parent + taxonomy + slug combinations are meant to be unique, and wp_insert_term()
  2266. * performs a last-minute confirmation of this uniqueness before allowing a new term
  2267. * to be created. Plugins with different uniqueness requirements may use this filter
  2268. * to bypass or modify the duplicate-term check.
  2269. *
  2270. * @since 5.1.0
  2271. *
  2272. * @param object $duplicate_term Duplicate term row from terms table, if found.
  2273. * @param string $term Term being inserted.
  2274. * @param string $taxonomy Taxonomy name.
  2275. * @param array $args Arguments passed to wp_insert_term().
  2276. * @param int $tt_id term_taxonomy_id for the newly created term.
  2277. */
  2278. $duplicate_term = apply_filters( 'wp_insert_term_duplicate_term_check', $duplicate_term, $term, $taxonomy, $args, $tt_id );
  2279. if ( $duplicate_term ) {
  2280. $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
  2281. $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
  2282. $term_id = (int) $duplicate_term->term_id;
  2283. $tt_id = (int) $duplicate_term->term_taxonomy_id;
  2284. clean_term_cache( $term_id, $taxonomy );
  2285. return array(
  2286. 'term_id' => $term_id,
  2287. 'term_taxonomy_id' => $tt_id,
  2288. );
  2289. }
  2290. /**
  2291. * Fires immediately after a new term is created, before the term cache is cleaned.
  2292. *
  2293. * The {@see 'create_$taxonomy'} hook is also available for targeting a specific
  2294. * taxonomy.
  2295. *
  2296. * @since 2.3.0
  2297. * @since 6.1.0 The `$args` parameter was added.
  2298. *
  2299. * @param int $term_id Term ID.
  2300. * @param int $tt_id Term taxonomy ID.
  2301. * @param string $taxonomy Taxonomy slug.
  2302. * @param array $args Arguments passed to wp_insert_term().
  2303. */
  2304. do_action( 'create_term', $term_id, $tt_id, $taxonomy, $args );
  2305. /**
  2306. * Fires after a new term is created for a specific taxonomy.
  2307. *
  2308. * The dynamic portion of the hook name, `$taxonomy`, refers
  2309. * to the slug of the taxonomy the term was created for.
  2310. *
  2311. * Possible hook names include:
  2312. *
  2313. * - `create_category`
  2314. * - `create_post_tag`
  2315. *
  2316. * @since 2.3.0
  2317. * @since 6.1.0 The `$args` parameter was added.
  2318. *
  2319. * @param int $term_id Term ID.
  2320. * @param int $tt_id Term taxonomy ID.
  2321. * @param array $args Arguments passed to wp_insert_term().
  2322. */
  2323. do_action( "create_{$taxonomy}", $term_id, $tt_id, $args );
  2324. /**
  2325. * Filters the term ID after a new term is created.
  2326. *
  2327. * @since 2.3.0
  2328. * @since 6.1.0 The `$args` parameter was added.
  2329. *
  2330. * @param int $term_id Term ID.
  2331. * @param int $tt_id Term taxonomy ID.
  2332. * @param array $args Arguments passed to wp_insert_term().
  2333. */
  2334. $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id, $args );
  2335. clean_term_cache( $term_id, $taxonomy );
  2336. /**
  2337. * Fires after a new term is created, and after the term cache has been cleaned.
  2338. *
  2339. * The {@see 'created_$taxonomy'} hook is also available for targeting a specific
  2340. * taxonomy.
  2341. *
  2342. * @since 2.3.0
  2343. * @since 6.1.0 The `$args` parameter was added.
  2344. *
  2345. * @param int $term_id Term ID.
  2346. * @param int $tt_id Term taxonomy ID.
  2347. * @param string $taxonomy Taxonomy slug.
  2348. * @param array $args Arguments passed to wp_insert_term().
  2349. */
  2350. do_action( 'created_term', $term_id, $tt_id, $taxonomy, $args );
  2351. /**
  2352. * Fires after a new term in a specific taxonomy is created, and after the term
  2353. * cache has been cleaned.
  2354. *
  2355. * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
  2356. *
  2357. * Possible hook names include:
  2358. *
  2359. * - `created_category`
  2360. * - `created_post_tag`
  2361. *
  2362. * @since 2.3.0
  2363. * @since 6.1.0 The `$args` parameter was added.
  2364. *
  2365. * @param int $term_id Term ID.
  2366. * @param int $tt_id Term taxonomy ID.
  2367. * @param array $args Arguments passed to wp_insert_term().
  2368. */
  2369. do_action( "created_{$taxonomy}", $term_id, $tt_id, $args );
  2370. /**
  2371. * Fires after a term has been saved, and the term cache has been cleared.
  2372. *
  2373. * The {@see 'saved_$taxonomy'} hook is also available for targeting a specific
  2374. * taxonomy.
  2375. *
  2376. * @since 5.5.0
  2377. * @since 6.1.0 The `$args` parameter was added.
  2378. *
  2379. * @param int $term_id Term ID.
  2380. * @param int $tt_id Term taxonomy ID.
  2381. * @param string $taxonomy Taxonomy slug.
  2382. * @param bool $update Whether this is an existing term being updated.
  2383. * @param array $args Arguments passed to wp_insert_term().
  2384. */
  2385. do_action( 'saved_term', $term_id, $tt_id, $taxonomy, false, $args );
  2386. /**
  2387. * Fires after a term in a specific taxonomy has been saved, and the term
  2388. * cache has been cleared.
  2389. *
  2390. * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
  2391. *
  2392. * Possible hook names include:
  2393. *
  2394. * - `saved_category`
  2395. * - `saved_post_tag`
  2396. *
  2397. * @since 5.5.0
  2398. * @since 6.1.0 The `$args` parameter was added.
  2399. *
  2400. * @param int $term_id Term ID.
  2401. * @param int $tt_id Term taxonomy ID.
  2402. * @param bool $update Whether this is an existing term being updated.
  2403. * @param array $args Arguments passed to wp_insert_term().
  2404. */
  2405. do_action( "saved_{$taxonomy}", $term_id, $tt_id, false, $args );
  2406. return array(
  2407. 'term_id' => $term_id,
  2408. 'term_taxonomy_id' => $tt_id,
  2409. );
  2410. }
  2411. /**
  2412. * Creates term and taxonomy relationships.
  2413. *
  2414. * Relates an object (post, link, etc.) to a term and taxonomy type. Creates the
  2415. * term and taxonomy relationship if it doesn't already exist. Creates a term if
  2416. * it doesn't exist (using the slug).
  2417. *
  2418. * A relationship means that the term is grouped in or belongs to the taxonomy.
  2419. * A term has no meaning until it is given context by defining which taxonomy it
  2420. * exists under.
  2421. *
  2422. * @since 2.3.0
  2423. *
  2424. * @global wpdb $wpdb WordPress database abstraction object.
  2425. *
  2426. * @param int $object_id The object to relate to.
  2427. * @param string|int|array $terms A single term slug, single term ID, or array of either term slugs or IDs.
  2428. * Will replace all existing related terms in this taxonomy. Passing an
  2429. * empty value will remove all related terms.
  2430. * @param string $taxonomy The context in which to relate the term to the object.
  2431. * @param bool $append Optional. If false will delete difference of terms. Default false.
  2432. * @return array|WP_Error Term taxonomy IDs of the affected terms or WP_Error on failure.
  2433. */
  2434. function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
  2435. global $wpdb;
  2436. $object_id = (int) $object_id;
  2437. if ( ! taxonomy_exists( $taxonomy ) ) {
  2438. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  2439. }
  2440. if ( ! is_array( $terms ) ) {
  2441. $terms = array( $terms );
  2442. }
  2443. if ( ! $append ) {
  2444. $old_tt_ids = wp_get_object_terms(
  2445. $object_id,
  2446. $taxonomy,
  2447. array(
  2448. 'fields' => 'tt_ids',
  2449. 'orderby' => 'none',
  2450. 'update_term_meta_cache' => false,
  2451. )
  2452. );
  2453. } else {
  2454. $old_tt_ids = array();
  2455. }
  2456. $tt_ids = array();
  2457. $term_ids = array();
  2458. $new_tt_ids = array();
  2459. foreach ( (array) $terms as $term ) {
  2460. if ( '' === trim( $term ) ) {
  2461. continue;
  2462. }
  2463. $term_info = term_exists( $term, $taxonomy );
  2464. if ( ! $term_info ) {
  2465. // Skip if a non-existent term ID is passed.
  2466. if ( is_int( $term ) ) {
  2467. continue;
  2468. }
  2469. $term_info = wp_insert_term( $term, $taxonomy );
  2470. }
  2471. if ( is_wp_error( $term_info ) ) {
  2472. return $term_info;
  2473. }
  2474. $term_ids[] = $term_info['term_id'];
  2475. $tt_id = $term_info['term_taxonomy_id'];
  2476. $tt_ids[] = $tt_id;
  2477. if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) ) {
  2478. continue;
  2479. }
  2480. /**
  2481. * Fires immediately before an object-term relationship is added.
  2482. *
  2483. * @since 2.9.0
  2484. * @since 4.7.0 Added the `$taxonomy` parameter.
  2485. *
  2486. * @param int $object_id Object ID.
  2487. * @param int $tt_id Term taxonomy ID.
  2488. * @param string $taxonomy Taxonomy slug.
  2489. */
  2490. do_action( 'add_term_relationship', $object_id, $tt_id, $taxonomy );
  2491. $wpdb->insert(
  2492. $wpdb->term_relationships,
  2493. array(
  2494. 'object_id' => $object_id,
  2495. 'term_taxonomy_id' => $tt_id,
  2496. )
  2497. );
  2498. /**
  2499. * Fires immediately after an object-term relationship is added.
  2500. *
  2501. * @since 2.9.0
  2502. * @since 4.7.0 Added the `$taxonomy` parameter.
  2503. *
  2504. * @param int $object_id Object ID.
  2505. * @param int $tt_id Term taxonomy ID.
  2506. * @param string $taxonomy Taxonomy slug.
  2507. */
  2508. do_action( 'added_term_relationship', $object_id, $tt_id, $taxonomy );
  2509. $new_tt_ids[] = $tt_id;
  2510. }
  2511. if ( $new_tt_ids ) {
  2512. wp_update_term_count( $new_tt_ids, $taxonomy );
  2513. }
  2514. if ( ! $append ) {
  2515. $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
  2516. if ( $delete_tt_ids ) {
  2517. $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
  2518. $delete_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) );
  2519. $delete_term_ids = array_map( 'intval', $delete_term_ids );
  2520. $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
  2521. if ( is_wp_error( $remove ) ) {
  2522. return $remove;
  2523. }
  2524. }
  2525. }
  2526. $t = get_taxonomy( $taxonomy );
  2527. if ( ! $append && isset( $t->sort ) && $t->sort ) {
  2528. $values = array();
  2529. $term_order = 0;
  2530. $final_tt_ids = wp_get_object_terms(
  2531. $object_id,
  2532. $taxonomy,
  2533. array(
  2534. 'fields' => 'tt_ids',
  2535. 'update_term_meta_cache' => false,
  2536. )
  2537. );
  2538. foreach ( $tt_ids as $tt_id ) {
  2539. if ( in_array( (int) $tt_id, $final_tt_ids, true ) ) {
  2540. $values[] = $wpdb->prepare( '(%d, %d, %d)', $object_id, $tt_id, ++$term_order );
  2541. }
  2542. }
  2543. if ( $values ) {
  2544. if ( false === $wpdb->query( "INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . implode( ',', $values ) . ' ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)' ) ) {
  2545. return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database.' ), $wpdb->last_error );
  2546. }
  2547. }
  2548. }
  2549. wp_cache_delete( $object_id, $taxonomy . '_relationships' );
  2550. wp_cache_delete( 'last_changed', 'terms' );
  2551. /**
  2552. * Fires after an object's terms have been set.
  2553. *
  2554. * @since 2.8.0
  2555. *
  2556. * @param int $object_id Object ID.
  2557. * @param array $terms An array of object term IDs or slugs.
  2558. * @param array $tt_ids An array of term taxonomy IDs.
  2559. * @param string $taxonomy Taxonomy slug.
  2560. * @param bool $append Whether to append new terms to the old terms.
  2561. * @param array $old_tt_ids Old array of term taxonomy IDs.
  2562. */
  2563. do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
  2564. return $tt_ids;
  2565. }
  2566. /**
  2567. * Adds term(s) associated with a given object.
  2568. *
  2569. * @since 3.6.0
  2570. *
  2571. * @param int $object_id The ID of the object to which the terms will be added.
  2572. * @param string|int|array $terms The slug(s) or ID(s) of the term(s) to add.
  2573. * @param array|string $taxonomy Taxonomy name.
  2574. * @return array|WP_Error Term taxonomy IDs of the affected terms.
  2575. */
  2576. function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
  2577. return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
  2578. }
  2579. /**
  2580. * Removes term(s) associated with a given object.
  2581. *
  2582. * @since 3.6.0
  2583. *
  2584. * @global wpdb $wpdb WordPress database abstraction object.
  2585. *
  2586. * @param int $object_id The ID of the object from which the terms will be removed.
  2587. * @param string|int|array $terms The slug(s) or ID(s) of the term(s) to remove.
  2588. * @param string $taxonomy Taxonomy name.
  2589. * @return bool|WP_Error True on success, false or WP_Error on failure.
  2590. */
  2591. function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
  2592. global $wpdb;
  2593. $object_id = (int) $object_id;
  2594. if ( ! taxonomy_exists( $taxonomy ) ) {
  2595. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  2596. }
  2597. if ( ! is_array( $terms ) ) {
  2598. $terms = array( $terms );
  2599. }
  2600. $tt_ids = array();
  2601. foreach ( (array) $terms as $term ) {
  2602. if ( '' === trim( $term ) ) {
  2603. continue;
  2604. }
  2605. $term_info = term_exists( $term, $taxonomy );
  2606. if ( ! $term_info ) {
  2607. // Skip if a non-existent term ID is passed.
  2608. if ( is_int( $term ) ) {
  2609. continue;
  2610. }
  2611. }
  2612. if ( is_wp_error( $term_info ) ) {
  2613. return $term_info;
  2614. }
  2615. $tt_ids[] = $term_info['term_taxonomy_id'];
  2616. }
  2617. if ( $tt_ids ) {
  2618. $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
  2619. /**
  2620. * Fires immediately before an object-term relationship is deleted.
  2621. *
  2622. * @since 2.9.0
  2623. * @since 4.7.0 Added the `$taxonomy` parameter.
  2624. *
  2625. * @param int $object_id Object ID.
  2626. * @param array $tt_ids An array of term taxonomy IDs.
  2627. * @param string $taxonomy Taxonomy slug.
  2628. */
  2629. do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy );
  2630. $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
  2631. wp_cache_delete( $object_id, $taxonomy . '_relationships' );
  2632. wp_cache_delete( 'last_changed', 'terms' );
  2633. /**
  2634. * Fires immediately after an object-term relationship is deleted.
  2635. *
  2636. * @since 2.9.0
  2637. * @since 4.7.0 Added the `$taxonomy` parameter.
  2638. *
  2639. * @param int $object_id Object ID.
  2640. * @param array $tt_ids An array of term taxonomy IDs.
  2641. * @param string $taxonomy Taxonomy slug.
  2642. */
  2643. do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
  2644. wp_update_term_count( $tt_ids, $taxonomy );
  2645. return (bool) $deleted;
  2646. }
  2647. return false;
  2648. }
  2649. /**
  2650. * Makes term slug unique, if it isn't already.
  2651. *
  2652. * The `$slug` has to be unique global to every taxonomy, meaning that one
  2653. * taxonomy term can't have a matching slug with another taxonomy term. Each
  2654. * slug has to be globally unique for every taxonomy.
  2655. *
  2656. * The way this works is that if the taxonomy that the term belongs to is
  2657. * hierarchical and has a parent, it will append that parent to the $slug.
  2658. *
  2659. * If that still doesn't return a unique slug, then it tries to append a number
  2660. * until it finds a number that is truly unique.
  2661. *
  2662. * The only purpose for `$term` is for appending a parent, if one exists.
  2663. *
  2664. * @since 2.3.0
  2665. *
  2666. * @global wpdb $wpdb WordPress database abstraction object.
  2667. *
  2668. * @param string $slug The string that will be tried for a unique slug.
  2669. * @param object $term The term object that the `$slug` will belong to.
  2670. * @return string Will return a true unique slug.
  2671. */
  2672. function wp_unique_term_slug( $slug, $term ) {
  2673. global $wpdb;
  2674. $needs_suffix = true;
  2675. $original_slug = $slug;
  2676. // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
  2677. if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
  2678. $needs_suffix = false;
  2679. }
  2680. /*
  2681. * If the taxonomy supports hierarchy and the term has a parent, make the slug unique
  2682. * by incorporating parent slugs.
  2683. */
  2684. $parent_suffix = '';
  2685. if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) {
  2686. $the_parent = $term->parent;
  2687. while ( ! empty( $the_parent ) ) {
  2688. $parent_term = get_term( $the_parent, $term->taxonomy );
  2689. if ( is_wp_error( $parent_term ) || empty( $parent_term ) ) {
  2690. break;
  2691. }
  2692. $parent_suffix .= '-' . $parent_term->slug;
  2693. if ( ! term_exists( $slug . $parent_suffix ) ) {
  2694. break;
  2695. }
  2696. if ( empty( $parent_term->parent ) ) {
  2697. break;
  2698. }
  2699. $the_parent = $parent_term->parent;
  2700. }
  2701. }
  2702. // If we didn't get a unique slug, try appending a number to make it unique.
  2703. /**
  2704. * Filters whether the proposed unique term slug is bad.
  2705. *
  2706. * @since 4.3.0
  2707. *
  2708. * @param bool $needs_suffix Whether the slug needs to be made unique with a suffix.
  2709. * @param string $slug The slug.
  2710. * @param object $term Term object.
  2711. */
  2712. if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) {
  2713. if ( $parent_suffix ) {
  2714. $slug .= $parent_suffix;
  2715. }
  2716. if ( ! empty( $term->term_id ) ) {
  2717. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
  2718. } else {
  2719. $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
  2720. }
  2721. if ( $wpdb->get_var( $query ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
  2722. $num = 2;
  2723. do {
  2724. $alt_slug = $slug . "-$num";
  2725. $num++;
  2726. $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
  2727. } while ( $slug_check );
  2728. $slug = $alt_slug;
  2729. }
  2730. }
  2731. /**
  2732. * Filters the unique term slug.
  2733. *
  2734. * @since 4.3.0
  2735. *
  2736. * @param string $slug Unique term slug.
  2737. * @param object $term Term object.
  2738. * @param string $original_slug Slug originally passed to the function for testing.
  2739. */
  2740. return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug );
  2741. }
  2742. /**
  2743. * Updates term based on arguments provided.
  2744. *
  2745. * The `$args` will indiscriminately override all values with the same field name.
  2746. * Care must be taken to not override important information need to update or
  2747. * update will fail (or perhaps create a new term, neither would be acceptable).
  2748. *
  2749. * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
  2750. * defined in `$args` already.
  2751. *
  2752. * 'alias_of' will create a term group, if it doesn't already exist, and
  2753. * update it for the `$term`.
  2754. *
  2755. * If the 'slug' argument in `$args` is missing, then the 'name' will be used.
  2756. * If you set 'slug' and it isn't unique, then a WP_Error is returned.
  2757. * If you don't pass any slug, then a unique one will be created.
  2758. *
  2759. * @since 2.3.0
  2760. *
  2761. * @global wpdb $wpdb WordPress database abstraction object.
  2762. *
  2763. * @param int $term_id The ID of the term.
  2764. * @param string $taxonomy The taxonomy of the term.
  2765. * @param array $args {
  2766. * Optional. Array of arguments for updating a term.
  2767. *
  2768. * @type string $alias_of Slug of the term to make this term an alias of.
  2769. * Default empty string. Accepts a term slug.
  2770. * @type string $description The term description. Default empty string.
  2771. * @type int $parent The id of the parent term. Default 0.
  2772. * @type string $slug The term slug to use. Default empty string.
  2773. * }
  2774. * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
  2775. * WP_Error otherwise.
  2776. */
  2777. function wp_update_term( $term_id, $taxonomy, $args = array() ) {
  2778. global $wpdb;
  2779. if ( ! taxonomy_exists( $taxonomy ) ) {
  2780. return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
  2781. }
  2782. $term_id = (int) $term_id;
  2783. // First, get all of the original args.
  2784. $term = get_term( $term_id, $taxonomy );
  2785. if ( is_wp_error( $term ) ) {
  2786. return $term;
  2787. }
  2788. if ( ! $term ) {
  2789. return new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
  2790. }
  2791. $term = (array) $term->data;
  2792. // Escape data pulled from DB.
  2793. $term = wp_slash( $term );
  2794. // Merge old and new args with new args overwriting old ones.
  2795. $args = array_merge( $term, $args );
  2796. $defaults = array(
  2797. 'alias_of' => '',
  2798. 'description' => '',
  2799. 'parent' => 0,
  2800. 'slug' => '',
  2801. );
  2802. $args = wp_parse_args( $args, $defaults );
  2803. $args = sanitize_term( $args, $taxonomy, 'db' );
  2804. $parsed_args = $args;
  2805. // expected_slashed ($name)
  2806. $name = wp_unslash( $args['name'] );
  2807. $description = wp_unslash( $args['description'] );
  2808. $parsed_args['name'] = $name;
  2809. $parsed_args['description'] = $description;
  2810. if ( '' === trim( $name ) ) {
  2811. return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
  2812. }
  2813. if ( (int) $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
  2814. return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
  2815. }
  2816. $empty_slug = false;
  2817. if ( empty( $args['slug'] ) ) {
  2818. $empty_slug = true;
  2819. $slug = sanitize_title( $name );
  2820. } else {
  2821. $slug = $args['slug'];
  2822. }
  2823. $parsed_args['slug'] = $slug;
  2824. $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
  2825. if ( $args['alias_of'] ) {
  2826. $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
  2827. if ( ! empty( $alias->term_group ) ) {
  2828. // The alias we want is already in a group, so let's use that one.
  2829. $term_group = $alias->term_group;
  2830. } elseif ( ! empty( $alias->term_id ) ) {
  2831. /*
  2832. * The alias is not in a group, so we create a new one
  2833. * and add the alias to it.
  2834. */
  2835. $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1;
  2836. wp_update_term(
  2837. $alias->term_id,
  2838. $taxonomy,
  2839. array(
  2840. 'term_group' => $term_group,
  2841. )
  2842. );
  2843. }
  2844. $parsed_args['term_group'] = $term_group;
  2845. }
  2846. /**
  2847. * Filters the term parent.
  2848. *
  2849. * Hook to this filter to see if it will cause a hierarchy loop.
  2850. *
  2851. * @since 3.1.0
  2852. *
  2853. * @param int $parent ID of the parent term.
  2854. * @param int $term_id Term ID.
  2855. * @param string $taxonomy Taxonomy slug.
  2856. * @param array $parsed_args An array of potentially altered update arguments for the given term.
  2857. * @param array $args Arguments passed to wp_update_term().
  2858. */
  2859. $parent = (int) apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
  2860. // Check for duplicate slug.
  2861. $duplicate = get_term_by( 'slug', $slug, $taxonomy );
  2862. if ( $duplicate && $duplicate->term_id !== $term_id ) {
  2863. // If an empty slug was passed or the parent changed, reset the slug to something unique.
  2864. // Otherwise, bail.
  2865. if ( $empty_slug || ( $parent !== (int) $term['parent'] ) ) {
  2866. $slug = wp_unique_term_slug( $slug, (object) $args );
  2867. } else {
  2868. /* translators: %s: Taxonomy term slug. */
  2869. return new WP_Error( 'duplicate_term_slug', sprintf( __( 'The slug &#8220;%s&#8221; is already in use by another term.' ), $slug ) );
  2870. }
  2871. }
  2872. $tt_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
  2873. // Check whether this is a shared term that needs splitting.
  2874. $_term_id = _split_shared_term( $term_id, $tt_id );
  2875. if ( ! is_wp_error( $_term_id ) ) {
  2876. $term_id = $_term_id;
  2877. }
  2878. /**
  2879. * Fires immediately before the given terms are edited.
  2880. *
  2881. * @since 2.9.0
  2882. * @since 6.1.0 The `$args` parameter was added.
  2883. *
  2884. * @param int $term_id Term ID.
  2885. * @param string $taxonomy Taxonomy slug.
  2886. * @param array $args Arguments passed to wp_update_term().
  2887. */
  2888. do_action( 'edit_terms', $term_id, $taxonomy, $args );
  2889. $data = compact( 'name', 'slug', 'term_group' );
  2890. /**
  2891. * Filters term data before it is updated in the database.
  2892. *
  2893. * @since 4.7.0
  2894. *
  2895. * @param array $data Term data to be updated.
  2896. * @param int $term_id Term ID.
  2897. * @param string $taxonomy Taxonomy slug.
  2898. * @param array $args Arguments passed to wp_update_term().
  2899. */
  2900. $data = apply_filters( 'wp_update_term_data', $data, $term_id, $taxonomy, $args );
  2901. $wpdb->update( $wpdb->terms, $data, compact( 'term_id' ) );
  2902. if ( empty( $slug ) ) {
  2903. $slug = sanitize_title( $name, $term_id );
  2904. $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
  2905. }
  2906. /**
  2907. * Fires immediately after a term is updated in the database, but before its
  2908. * term-taxonomy relationship is updated.
  2909. *
  2910. * @since 2.9.0
  2911. * @since 6.1.0 The `$args` parameter was added.
  2912. *
  2913. * @param int $term_id Term ID.
  2914. * @param string $taxonomy Taxonomy slug.
  2915. * @param array $args Arguments passed to wp_update_term().
  2916. */
  2917. do_action( 'edited_terms', $term_id, $taxonomy, $args );
  2918. /**
  2919. * Fires immediate before a term-taxonomy relationship is updated.
  2920. *
  2921. * @since 2.9.0
  2922. * @since 6.1.0 The `$args` parameter was added.
  2923. *
  2924. * @param int $tt_id Term taxonomy ID.
  2925. * @param string $taxonomy Taxonomy slug.
  2926. * @param array $args Arguments passed to wp_update_term().
  2927. */
  2928. do_action( 'edit_term_taxonomy', $tt_id, $taxonomy, $args );
  2929. $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
  2930. /**
  2931. * Fires immediately after a term-taxonomy relationship is updated.
  2932. *
  2933. * @since 2.9.0
  2934. * @since 6.1.0 The `$args` parameter was added.
  2935. *
  2936. * @param int $tt_id Term taxonomy ID.
  2937. * @param string $taxonomy Taxonomy slug.
  2938. * @param array $args Arguments passed to wp_update_term().
  2939. */
  2940. do_action( 'edited_term_taxonomy', $tt_id, $taxonomy, $args );
  2941. /**
  2942. * Fires after a term has been updated, but before the term cache has been cleaned.
  2943. *
  2944. * The {@see 'edit_$taxonomy'} hook is also available for targeting a specific
  2945. * taxonomy.
  2946. *
  2947. * @since 2.3.0
  2948. * @since 6.1.0 The `$args` parameter was added.
  2949. *
  2950. * @param int $term_id Term ID.
  2951. * @param int $tt_id Term taxonomy ID.
  2952. * @param string $taxonomy Taxonomy slug.
  2953. * @param array $args Arguments passed to wp_update_term().
  2954. */
  2955. do_action( 'edit_term', $term_id, $tt_id, $taxonomy, $args );
  2956. /**
  2957. * Fires after a term in a specific taxonomy has been updated, but before the term
  2958. * cache has been cleaned.
  2959. *
  2960. * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
  2961. *
  2962. * Possible hook names include:
  2963. *
  2964. * - `edit_category`
  2965. * - `edit_post_tag`
  2966. *
  2967. * @since 2.3.0
  2968. * @since 6.1.0 The `$args` parameter was added.
  2969. *
  2970. * @param int $term_id Term ID.
  2971. * @param int $tt_id Term taxonomy ID.
  2972. * @param array $args Arguments passed to wp_update_term().
  2973. */
  2974. do_action( "edit_{$taxonomy}", $term_id, $tt_id, $args );
  2975. /** This filter is documented in wp-includes/taxonomy.php */
  2976. $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
  2977. clean_term_cache( $term_id, $taxonomy );
  2978. /**
  2979. * Fires after a term has been updated, and the term cache has been cleaned.
  2980. *
  2981. * The {@see 'edited_$taxonomy'} hook is also available for targeting a specific
  2982. * taxonomy.
  2983. *
  2984. * @since 2.3.0
  2985. * @since 6.1.0 The `$args` parameter was added.
  2986. *
  2987. * @param int $term_id Term ID.
  2988. * @param int $tt_id Term taxonomy ID.
  2989. * @param string $taxonomy Taxonomy slug.
  2990. * @param array $args Arguments passed to wp_update_term().
  2991. */
  2992. do_action( 'edited_term', $term_id, $tt_id, $taxonomy, $args );
  2993. /**
  2994. * Fires after a term for a specific taxonomy has been updated, and the term
  2995. * cache has been cleaned.
  2996. *
  2997. * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
  2998. *
  2999. * Possible hook names include:
  3000. *
  3001. * - `edited_category`
  3002. * - `edited_post_tag`
  3003. *
  3004. * @since 2.3.0
  3005. * @since 6.1.0 The `$args` parameter was added.
  3006. *
  3007. * @param int $term_id Term ID.
  3008. * @param int $tt_id Term taxonomy ID.
  3009. * @param array $args Arguments passed to wp_update_term().
  3010. */
  3011. do_action( "edited_{$taxonomy}", $term_id, $tt_id, $args );
  3012. /** This action is documented in wp-includes/taxonomy.php */
  3013. do_action( 'saved_term', $term_id, $tt_id, $taxonomy, true, $args );
  3014. /** This action is documented in wp-includes/taxonomy.php */
  3015. do_action( "saved_{$taxonomy}", $term_id, $tt_id, true, $args );
  3016. return array(
  3017. 'term_id' => $term_id,
  3018. 'term_taxonomy_id' => $tt_id,
  3019. );
  3020. }
  3021. /**
  3022. * Enables or disables term counting.
  3023. *
  3024. * @since 2.5.0
  3025. *
  3026. * @param bool $defer Optional. Enable if true, disable if false.
  3027. * @return bool Whether term counting is enabled or disabled.
  3028. */
  3029. function wp_defer_term_counting( $defer = null ) {
  3030. static $_defer = false;
  3031. if ( is_bool( $defer ) ) {
  3032. $_defer = $defer;
  3033. // Flush any deferred counts.
  3034. if ( ! $defer ) {
  3035. wp_update_term_count( null, null, true );
  3036. }
  3037. }
  3038. return $_defer;
  3039. }
  3040. /**
  3041. * Updates the amount of terms in taxonomy.
  3042. *
  3043. * If there is a taxonomy callback applied, then it will be called for updating
  3044. * the count.
  3045. *
  3046. * The default action is to count what the amount of terms have the relationship
  3047. * of term ID. Once that is done, then update the database.
  3048. *
  3049. * @since 2.3.0
  3050. *
  3051. * @param int|array $terms The term_taxonomy_id of the terms.
  3052. * @param string $taxonomy The context of the term.
  3053. * @param bool $do_deferred Whether to flush the deferred term counts too. Default false.
  3054. * @return bool If no terms will return false, and if successful will return true.
  3055. */
  3056. function wp_update_term_count( $terms, $taxonomy, $do_deferred = false ) {
  3057. static $_deferred = array();
  3058. if ( $do_deferred ) {
  3059. foreach ( (array) array_keys( $_deferred ) as $tax ) {
  3060. wp_update_term_count_now( $_deferred[ $tax ], $tax );
  3061. unset( $_deferred[ $tax ] );
  3062. }
  3063. }
  3064. if ( empty( $terms ) ) {
  3065. return false;
  3066. }
  3067. if ( ! is_array( $terms ) ) {
  3068. $terms = array( $terms );
  3069. }
  3070. if ( wp_defer_term_counting() ) {
  3071. if ( ! isset( $_deferred[ $taxonomy ] ) ) {
  3072. $_deferred[ $taxonomy ] = array();
  3073. }
  3074. $_deferred[ $taxonomy ] = array_unique( array_merge( $_deferred[ $taxonomy ], $terms ) );
  3075. return true;
  3076. }
  3077. return wp_update_term_count_now( $terms, $taxonomy );
  3078. }
  3079. /**
  3080. * Performs term count update immediately.
  3081. *
  3082. * @since 2.5.0
  3083. *
  3084. * @param array $terms The term_taxonomy_id of terms to update.
  3085. * @param string $taxonomy The context of the term.
  3086. * @return true Always true when complete.
  3087. */
  3088. function wp_update_term_count_now( $terms, $taxonomy ) {
  3089. $terms = array_map( 'intval', $terms );
  3090. $taxonomy = get_taxonomy( $taxonomy );
  3091. if ( ! empty( $taxonomy->update_count_callback ) ) {
  3092. call_user_func( $taxonomy->update_count_callback, $terms, $taxonomy );
  3093. } else {
  3094. $object_types = (array) $taxonomy->object_type;
  3095. foreach ( $object_types as &$object_type ) {
  3096. if ( 0 === strpos( $object_type, 'attachment:' ) ) {
  3097. list( $object_type ) = explode( ':', $object_type );
  3098. }
  3099. }
  3100. if ( array_filter( $object_types, 'post_type_exists' ) == $object_types ) {
  3101. // Only post types are attached to this taxonomy.
  3102. _update_post_term_count( $terms, $taxonomy );
  3103. } else {
  3104. // Default count updater.
  3105. _update_generic_term_count( $terms, $taxonomy );
  3106. }
  3107. }
  3108. clean_term_cache( $terms, '', false );
  3109. return true;
  3110. }
  3111. //
  3112. // Cache.
  3113. //
  3114. /**
  3115. * Removes the taxonomy relationship to terms from the cache.
  3116. *
  3117. * Will remove the entire taxonomy relationship containing term `$object_id`. The
  3118. * term IDs have to exist within the taxonomy `$object_type` for the deletion to
  3119. * take place.
  3120. *
  3121. * @since 2.3.0
  3122. *
  3123. * @global bool $_wp_suspend_cache_invalidation
  3124. *
  3125. * @see get_object_taxonomies() for more on $object_type.
  3126. *
  3127. * @param int|array $object_ids Single or list of term object ID(s).
  3128. * @param array|string $object_type The taxonomy object type.
  3129. */
  3130. function clean_object_term_cache( $object_ids, $object_type ) {
  3131. global $_wp_suspend_cache_invalidation;
  3132. if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
  3133. return;
  3134. }
  3135. if ( ! is_array( $object_ids ) ) {
  3136. $object_ids = array( $object_ids );
  3137. }
  3138. $taxonomies = get_object_taxonomies( $object_type );
  3139. foreach ( $taxonomies as $taxonomy ) {
  3140. wp_cache_delete_multiple( $object_ids, "{$taxonomy}_relationships" );
  3141. }
  3142. wp_cache_delete( 'last_changed', 'terms' );
  3143. /**
  3144. * Fires after the object term cache has been cleaned.
  3145. *
  3146. * @since 2.5.0
  3147. *
  3148. * @param array $object_ids An array of object IDs.
  3149. * @param string $object_type Object type.
  3150. */
  3151. do_action( 'clean_object_term_cache', $object_ids, $object_type );
  3152. }
  3153. /**
  3154. * Removes all of the term IDs from the cache.
  3155. *
  3156. * @since 2.3.0
  3157. *
  3158. * @global wpdb $wpdb WordPress database abstraction object.
  3159. * @global bool $_wp_suspend_cache_invalidation
  3160. *
  3161. * @param int|int[] $ids Single or array of term IDs.
  3162. * @param string $taxonomy Optional. Taxonomy slug. Can be empty, in which case the taxonomies of the passed
  3163. * term IDs will be used. Default empty.
  3164. * @param bool $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
  3165. * term object caches (false). Default true.
  3166. */
  3167. function clean_term_cache( $ids, $taxonomy = '', $clean_taxonomy = true ) {
  3168. global $wpdb, $_wp_suspend_cache_invalidation;
  3169. if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
  3170. return;
  3171. }
  3172. if ( ! is_array( $ids ) ) {
  3173. $ids = array( $ids );
  3174. }
  3175. $taxonomies = array();
  3176. // If no taxonomy, assume tt_ids.
  3177. if ( empty( $taxonomy ) ) {
  3178. $tt_ids = array_map( 'intval', $ids );
  3179. $tt_ids = implode( ', ', $tt_ids );
  3180. $terms = $wpdb->get_results( "SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)" );
  3181. $ids = array();
  3182. foreach ( (array) $terms as $term ) {
  3183. $taxonomies[] = $term->taxonomy;
  3184. $ids[] = $term->term_id;
  3185. }
  3186. wp_cache_delete_multiple( $ids, 'terms' );
  3187. $taxonomies = array_unique( $taxonomies );
  3188. } else {
  3189. wp_cache_delete_multiple( $ids, 'terms' );
  3190. $taxonomies = array( $taxonomy );
  3191. }
  3192. foreach ( $taxonomies as $taxonomy ) {
  3193. if ( $clean_taxonomy ) {
  3194. clean_taxonomy_cache( $taxonomy );
  3195. }
  3196. /**
  3197. * Fires once after each taxonomy's term cache has been cleaned.
  3198. *
  3199. * @since 2.5.0
  3200. * @since 4.5.0 Added the `$clean_taxonomy` parameter.
  3201. *
  3202. * @param array $ids An array of term IDs.
  3203. * @param string $taxonomy Taxonomy slug.
  3204. * @param bool $clean_taxonomy Whether or not to clean taxonomy-wide caches
  3205. */
  3206. do_action( 'clean_term_cache', $ids, $taxonomy, $clean_taxonomy );
  3207. }
  3208. wp_cache_set( 'last_changed', microtime(), 'terms' );
  3209. }
  3210. /**
  3211. * Cleans the caches for a taxonomy.
  3212. *
  3213. * @since 4.9.0
  3214. *
  3215. * @param string $taxonomy Taxonomy slug.
  3216. */
  3217. function clean_taxonomy_cache( $taxonomy ) {
  3218. wp_cache_delete( 'all_ids', $taxonomy );
  3219. wp_cache_delete( 'get', $taxonomy );
  3220. wp_cache_delete( 'last_changed', 'terms' );
  3221. // Regenerate cached hierarchy.
  3222. delete_option( "{$taxonomy}_children" );
  3223. _get_term_hierarchy( $taxonomy );
  3224. /**
  3225. * Fires after a taxonomy's caches have been cleaned.
  3226. *
  3227. * @since 4.9.0
  3228. *
  3229. * @param string $taxonomy Taxonomy slug.
  3230. */
  3231. do_action( 'clean_taxonomy_cache', $taxonomy );
  3232. }
  3233. /**
  3234. * Retrieves the cached term objects for the given object ID.
  3235. *
  3236. * Upstream functions (like get_the_terms() and is_object_in_term()) are
  3237. * responsible for populating the object-term relationship cache. The current
  3238. * function only fetches relationship data that is already in the cache.
  3239. *
  3240. * @since 2.3.0
  3241. * @since 4.7.0 Returns a `WP_Error` object if there's an error with
  3242. * any of the matched terms.
  3243. *
  3244. * @param int $id Term object ID, for example a post, comment, or user ID.
  3245. * @param string $taxonomy Taxonomy name.
  3246. * @return bool|WP_Term[]|WP_Error Array of `WP_Term` objects, if cached.
  3247. * False if cache is empty for `$taxonomy` and `$id`.
  3248. * WP_Error if get_term() returns an error object for any term.
  3249. */
  3250. function get_object_term_cache( $id, $taxonomy ) {
  3251. $_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
  3252. // We leave the priming of relationship caches to upstream functions.
  3253. if ( false === $_term_ids ) {
  3254. return false;
  3255. }
  3256. // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
  3257. $term_ids = array();
  3258. foreach ( $_term_ids as $term_id ) {
  3259. if ( is_numeric( $term_id ) ) {
  3260. $term_ids[] = (int) $term_id;
  3261. } elseif ( isset( $term_id->term_id ) ) {
  3262. $term_ids[] = (int) $term_id->term_id;
  3263. }
  3264. }
  3265. // Fill the term objects.
  3266. _prime_term_caches( $term_ids );
  3267. $terms = array();
  3268. foreach ( $term_ids as $term_id ) {
  3269. $term = get_term( $term_id, $taxonomy );
  3270. if ( is_wp_error( $term ) ) {
  3271. return $term;
  3272. }
  3273. $terms[] = $term;
  3274. }
  3275. return $terms;
  3276. }
  3277. /**
  3278. * Updates the cache for the given term object ID(s).
  3279. *
  3280. * Note: Due to performance concerns, great care should be taken to only update
  3281. * term caches when necessary. Processing time can increase exponentially depending
  3282. * on both the number of passed term IDs and the number of taxonomies those terms
  3283. * belong to.
  3284. *
  3285. * Caches will only be updated for terms not already cached.
  3286. *
  3287. * @since 2.3.0
  3288. *
  3289. * @param string|int[] $object_ids Comma-separated list or array of term object IDs.
  3290. * @param string|string[] $object_type The taxonomy object type or array of the same.
  3291. * @return void|false Void on success or if the `$object_ids` parameter is empty,
  3292. * false if all of the terms in `$object_ids` are already cached.
  3293. */
  3294. function update_object_term_cache( $object_ids, $object_type ) {
  3295. if ( empty( $object_ids ) ) {
  3296. return;
  3297. }
  3298. if ( ! is_array( $object_ids ) ) {
  3299. $object_ids = explode( ',', $object_ids );
  3300. }
  3301. $object_ids = array_map( 'intval', $object_ids );
  3302. $non_cached_ids = array();
  3303. $taxonomies = get_object_taxonomies( $object_type );
  3304. foreach ( $taxonomies as $taxonomy ) {
  3305. $cache_values = wp_cache_get_multiple( (array) $object_ids, "{$taxonomy}_relationships" );
  3306. foreach ( $cache_values as $id => $value ) {
  3307. if ( false === $value ) {
  3308. $non_cached_ids[] = $id;
  3309. }
  3310. }
  3311. }
  3312. if ( empty( $non_cached_ids ) ) {
  3313. return false;
  3314. }
  3315. $non_cached_ids = array_unique( $non_cached_ids );
  3316. $terms = wp_get_object_terms(
  3317. $non_cached_ids,
  3318. $taxonomies,
  3319. array(
  3320. 'fields' => 'all_with_object_id',
  3321. 'orderby' => 'name',
  3322. 'update_term_meta_cache' => false,
  3323. )
  3324. );
  3325. $object_terms = array();
  3326. foreach ( (array) $terms as $term ) {
  3327. $object_terms[ $term->object_id ][ $term->taxonomy ][] = $term->term_id;
  3328. }
  3329. foreach ( $non_cached_ids as $id ) {
  3330. foreach ( $taxonomies as $taxonomy ) {
  3331. if ( ! isset( $object_terms[ $id ][ $taxonomy ] ) ) {
  3332. if ( ! isset( $object_terms[ $id ] ) ) {
  3333. $object_terms[ $id ] = array();
  3334. }
  3335. $object_terms[ $id ][ $taxonomy ] = array();
  3336. }
  3337. }
  3338. }
  3339. $cache_values = array();
  3340. foreach ( $object_terms as $id => $value ) {
  3341. foreach ( $value as $taxonomy => $terms ) {
  3342. $cache_values[ $taxonomy ][ $id ] = $terms;
  3343. }
  3344. }
  3345. foreach ( $cache_values as $taxonomy => $data ) {
  3346. wp_cache_add_multiple( $data, "{$taxonomy}_relationships" );
  3347. }
  3348. }
  3349. /**
  3350. * Updates terms in cache.
  3351. *
  3352. * @since 2.3.0
  3353. *
  3354. * @param WP_Term[] $terms Array of term objects to change.
  3355. * @param string $taxonomy Not used.
  3356. */
  3357. function update_term_cache( $terms, $taxonomy = '' ) {
  3358. $data = array();
  3359. foreach ( (array) $terms as $term ) {
  3360. // Create a copy in case the array was passed by reference.
  3361. $_term = clone $term;
  3362. // Object ID should not be cached.
  3363. unset( $_term->object_id );
  3364. $data[ $term->term_id ] = $_term;
  3365. }
  3366. wp_cache_add_multiple( $data, 'terms' );
  3367. }
  3368. //
  3369. // Private.
  3370. //
  3371. /**
  3372. * Retrieves children of taxonomy as term IDs.
  3373. *
  3374. * @access private
  3375. * @since 2.3.0
  3376. *
  3377. * @param string $taxonomy Taxonomy name.
  3378. * @return array Empty if $taxonomy isn't hierarchical or returns children as term IDs.
  3379. */
  3380. function _get_term_hierarchy( $taxonomy ) {
  3381. if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
  3382. return array();
  3383. }
  3384. $children = get_option( "{$taxonomy}_children" );
  3385. if ( is_array( $children ) ) {
  3386. return $children;
  3387. }
  3388. $children = array();
  3389. $terms = get_terms(
  3390. array(
  3391. 'taxonomy' => $taxonomy,
  3392. 'get' => 'all',
  3393. 'orderby' => 'id',
  3394. 'fields' => 'id=>parent',
  3395. 'update_term_meta_cache' => false,
  3396. )
  3397. );
  3398. foreach ( $terms as $term_id => $parent ) {
  3399. if ( $parent > 0 ) {
  3400. $children[ $parent ][] = $term_id;
  3401. }
  3402. }
  3403. update_option( "{$taxonomy}_children", $children );
  3404. return $children;
  3405. }
  3406. /**
  3407. * Gets the subset of $terms that are descendants of $term_id.
  3408. *
  3409. * If `$terms` is an array of objects, then _get_term_children() returns an array of objects.
  3410. * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs.
  3411. *
  3412. * @access private
  3413. * @since 2.3.0
  3414. *
  3415. * @param int $term_id The ancestor term: all returned terms should be descendants of `$term_id`.
  3416. * @param array $terms The set of terms - either an array of term objects or term IDs - from which those that
  3417. * are descendants of $term_id will be chosen.
  3418. * @param string $taxonomy The taxonomy which determines the hierarchy of the terms.
  3419. * @param array $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep
  3420. * track of found terms when recursing the hierarchy. The array of located ancestors is used
  3421. * to prevent infinite recursion loops. For performance, `term_ids` are used as array keys,
  3422. * with 1 as value. Default empty array.
  3423. * @return array|WP_Error The subset of $terms that are descendants of $term_id.
  3424. */
  3425. function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
  3426. $empty_array = array();
  3427. if ( empty( $terms ) ) {
  3428. return $empty_array;
  3429. }
  3430. $term_id = (int) $term_id;
  3431. $term_list = array();
  3432. $has_children = _get_term_hierarchy( $taxonomy );
  3433. if ( $term_id && ! isset( $has_children[ $term_id ] ) ) {
  3434. return $empty_array;
  3435. }
  3436. // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
  3437. if ( empty( $ancestors ) ) {
  3438. $ancestors[ $term_id ] = 1;
  3439. }
  3440. foreach ( (array) $terms as $term ) {
  3441. $use_id = false;
  3442. if ( ! is_object( $term ) ) {
  3443. $term = get_term( $term, $taxonomy );
  3444. if ( is_wp_error( $term ) ) {
  3445. return $term;
  3446. }
  3447. $use_id = true;
  3448. }
  3449. // Don't recurse if we've already identified the term as a child - this indicates a loop.
  3450. if ( isset( $ancestors[ $term->term_id ] ) ) {
  3451. continue;
  3452. }
  3453. if ( (int) $term->parent === $term_id ) {
  3454. if ( $use_id ) {
  3455. $term_list[] = $term->term_id;
  3456. } else {
  3457. $term_list[] = $term;
  3458. }
  3459. if ( ! isset( $has_children[ $term->term_id ] ) ) {
  3460. continue;
  3461. }
  3462. $ancestors[ $term->term_id ] = 1;
  3463. $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors );
  3464. if ( $children ) {
  3465. $term_list = array_merge( $term_list, $children );
  3466. }
  3467. }
  3468. }
  3469. return $term_list;
  3470. }
  3471. /**
  3472. * Adds count of children to parent count.
  3473. *
  3474. * Recalculates term counts by including items from child terms. Assumes all
  3475. * relevant children are already in the $terms argument.
  3476. *
  3477. * @access private
  3478. * @since 2.3.0
  3479. *
  3480. * @global wpdb $wpdb WordPress database abstraction object.
  3481. *
  3482. * @param object[]|WP_Term[] $terms List of term objects (passed by reference).
  3483. * @param string $taxonomy Term context.
  3484. */
  3485. function _pad_term_counts( &$terms, $taxonomy ) {
  3486. global $wpdb;
  3487. // This function only works for hierarchical taxonomies like post categories.
  3488. if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
  3489. return;
  3490. }
  3491. $term_hier = _get_term_hierarchy( $taxonomy );
  3492. if ( empty( $term_hier ) ) {
  3493. return;
  3494. }
  3495. $term_items = array();
  3496. $terms_by_id = array();
  3497. $term_ids = array();
  3498. foreach ( (array) $terms as $key => $term ) {
  3499. $terms_by_id[ $term->term_id ] = & $terms[ $key ];
  3500. $term_ids[ $term->term_taxonomy_id ] = $term->term_id;
  3501. }
  3502. // Get the object and term IDs and stick them in a lookup table.
  3503. $tax_obj = get_taxonomy( $taxonomy );
  3504. $object_types = esc_sql( $tax_obj->object_type );
  3505. $results = $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode( ',', array_keys( $term_ids ) ) . ") AND post_type IN ('" . implode( "', '", $object_types ) . "') AND post_status = 'publish'" );
  3506. foreach ( $results as $row ) {
  3507. $id = $term_ids[ $row->term_taxonomy_id ];
  3508. $term_items[ $id ][ $row->object_id ] = isset( $term_items[ $id ][ $row->object_id ] ) ? ++$term_items[ $id ][ $row->object_id ] : 1;
  3509. }
  3510. // Touch every ancestor's lookup row for each post in each term.
  3511. foreach ( $term_ids as $term_id ) {
  3512. $child = $term_id;
  3513. $ancestors = array();
  3514. while ( ! empty( $terms_by_id[ $child ] ) && $parent = $terms_by_id[ $child ]->parent ) {
  3515. $ancestors[] = $child;
  3516. if ( ! empty( $term_items[ $term_id ] ) ) {
  3517. foreach ( $term_items[ $term_id ] as $item_id => $touches ) {
  3518. $term_items[ $parent ][ $item_id ] = isset( $term_items[ $parent ][ $item_id ] ) ? ++$term_items[ $parent ][ $item_id ] : 1;
  3519. }
  3520. }
  3521. $child = $parent;
  3522. if ( in_array( $parent, $ancestors, true ) ) {
  3523. break;
  3524. }
  3525. }
  3526. }
  3527. // Transfer the touched cells.
  3528. foreach ( (array) $term_items as $id => $items ) {
  3529. if ( isset( $terms_by_id[ $id ] ) ) {
  3530. $terms_by_id[ $id ]->count = count( $items );
  3531. }
  3532. }
  3533. }
  3534. /**
  3535. * Adds any terms from the given IDs to the cache that do not already exist in cache.
  3536. *
  3537. * @since 4.6.0
  3538. * @since 6.1.0 This function is no longer marked as "private".
  3539. *
  3540. * @global wpdb $wpdb WordPress database abstraction object.
  3541. *
  3542. * @param array $term_ids Array of term IDs.
  3543. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  3544. */
  3545. function _prime_term_caches( $term_ids, $update_meta_cache = true ) {
  3546. global $wpdb;
  3547. $non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' );
  3548. if ( ! empty( $non_cached_ids ) ) {
  3549. $fresh_terms = $wpdb->get_results( sprintf( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) );
  3550. update_term_cache( $fresh_terms );
  3551. if ( $update_meta_cache ) {
  3552. update_termmeta_cache( $non_cached_ids );
  3553. }
  3554. }
  3555. }
  3556. //
  3557. // Default callbacks.
  3558. //
  3559. /**
  3560. * Updates term count based on object types of the current taxonomy.
  3561. *
  3562. * Private function for the default callback for post_tag and category
  3563. * taxonomies.
  3564. *
  3565. * @access private
  3566. * @since 2.3.0
  3567. *
  3568. * @global wpdb $wpdb WordPress database abstraction object.
  3569. *
  3570. * @param int[] $terms List of term taxonomy IDs.
  3571. * @param WP_Taxonomy $taxonomy Current taxonomy object of terms.
  3572. */
  3573. function _update_post_term_count( $terms, $taxonomy ) {
  3574. global $wpdb;
  3575. $object_types = (array) $taxonomy->object_type;
  3576. foreach ( $object_types as &$object_type ) {
  3577. list( $object_type ) = explode( ':', $object_type );
  3578. }
  3579. $object_types = array_unique( $object_types );
  3580. $check_attachments = array_search( 'attachment', $object_types, true );
  3581. if ( false !== $check_attachments ) {
  3582. unset( $object_types[ $check_attachments ] );
  3583. $check_attachments = true;
  3584. }
  3585. if ( $object_types ) {
  3586. $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
  3587. }
  3588. $post_statuses = array( 'publish' );
  3589. /**
  3590. * Filters the post statuses for updating the term count.
  3591. *
  3592. * @since 5.7.0
  3593. *
  3594. * @param string[] $post_statuses List of post statuses to include in the count. Default is 'publish'.
  3595. * @param WP_Taxonomy $taxonomy Current taxonomy object.
  3596. */
  3597. $post_statuses = esc_sql( apply_filters( 'update_post_term_count_statuses', $post_statuses, $taxonomy ) );
  3598. foreach ( (array) $terms as $term ) {
  3599. $count = 0;
  3600. // Attachments can be 'inherit' status, we need to base count off the parent's status if so.
  3601. if ( $check_attachments ) {
  3602. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration
  3603. $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status IN ('" . implode( "', '", $post_statuses ) . "') OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) IN ('" . implode( "', '", $post_statuses ) . "') ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) );
  3604. }
  3605. if ( $object_types ) {
  3606. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration
  3607. $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status IN ('" . implode( "', '", $post_statuses ) . "') AND post_type IN ('" . implode( "', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );
  3608. }
  3609. /** This action is documented in wp-includes/taxonomy.php */
  3610. do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
  3611. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  3612. /** This action is documented in wp-includes/taxonomy.php */
  3613. do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
  3614. }
  3615. }
  3616. /**
  3617. * Updates term count based on number of objects.
  3618. *
  3619. * Default callback for the 'link_category' taxonomy.
  3620. *
  3621. * @since 3.3.0
  3622. *
  3623. * @global wpdb $wpdb WordPress database abstraction object.
  3624. *
  3625. * @param int[] $terms List of term taxonomy IDs.
  3626. * @param WP_Taxonomy $taxonomy Current taxonomy object of terms.
  3627. */
  3628. function _update_generic_term_count( $terms, $taxonomy ) {
  3629. global $wpdb;
  3630. foreach ( (array) $terms as $term ) {
  3631. $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
  3632. /** This action is documented in wp-includes/taxonomy.php */
  3633. do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
  3634. $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
  3635. /** This action is documented in wp-includes/taxonomy.php */
  3636. do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
  3637. }
  3638. }
  3639. /**
  3640. * Creates a new term for a term_taxonomy item that currently shares its term
  3641. * with another term_taxonomy.
  3642. *
  3643. * @ignore
  3644. * @since 4.2.0
  3645. * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
  3646. * `$term_taxonomy_id` can now accept objects.
  3647. *
  3648. * @global wpdb $wpdb WordPress database abstraction object.
  3649. *
  3650. * @param int|object $term_id ID of the shared term, or the shared term object.
  3651. * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
  3652. * (corresponding to a row from the term_taxonomy table).
  3653. * @param bool $record Whether to record data about the split term in the options table. The recording
  3654. * process has the potential to be resource-intensive, so during batch operations
  3655. * it can be beneficial to skip inline recording and do it just once, after the
  3656. * batch is processed. Only set this to `false` if you know what you are doing.
  3657. * Default: true.
  3658. * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
  3659. * database schema), `$term_id` is returned. When the term is successfully split, the
  3660. * new term_id is returned. A WP_Error is returned for miscellaneous errors.
  3661. */
  3662. function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) {
  3663. global $wpdb;
  3664. if ( is_object( $term_id ) ) {
  3665. $shared_term = $term_id;
  3666. $term_id = (int) $shared_term->term_id;
  3667. }
  3668. if ( is_object( $term_taxonomy_id ) ) {
  3669. $term_taxonomy = $term_taxonomy_id;
  3670. $term_taxonomy_id = (int) $term_taxonomy->term_taxonomy_id;
  3671. }
  3672. // If there are no shared term_taxonomy rows, there's nothing to do here.
  3673. $shared_tt_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy tt WHERE tt.term_id = %d AND tt.term_taxonomy_id != %d", $term_id, $term_taxonomy_id ) );
  3674. if ( ! $shared_tt_count ) {
  3675. return $term_id;
  3676. }
  3677. /*
  3678. * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
  3679. * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
  3680. */
  3681. $check_term_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
  3682. if ( $check_term_id !== $term_id ) {
  3683. return $check_term_id;
  3684. }
  3685. // Pull up data about the currently shared slug, which we'll use to populate the new one.
  3686. if ( empty( $shared_term ) ) {
  3687. $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
  3688. }
  3689. $new_term_data = array(
  3690. 'name' => $shared_term->name,
  3691. 'slug' => $shared_term->slug,
  3692. 'term_group' => $shared_term->term_group,
  3693. );
  3694. if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
  3695. return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
  3696. }
  3697. $new_term_id = (int) $wpdb->insert_id;
  3698. // Update the existing term_taxonomy to point to the newly created term.
  3699. $wpdb->update(
  3700. $wpdb->term_taxonomy,
  3701. array( 'term_id' => $new_term_id ),
  3702. array( 'term_taxonomy_id' => $term_taxonomy_id )
  3703. );
  3704. // Reassign child terms to the new parent.
  3705. if ( empty( $term_taxonomy ) ) {
  3706. $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
  3707. }
  3708. $children_tt_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE parent = %d AND taxonomy = %s", $term_id, $term_taxonomy->taxonomy ) );
  3709. if ( ! empty( $children_tt_ids ) ) {
  3710. foreach ( $children_tt_ids as $child_tt_id ) {
  3711. $wpdb->update(
  3712. $wpdb->term_taxonomy,
  3713. array( 'parent' => $new_term_id ),
  3714. array( 'term_taxonomy_id' => $child_tt_id )
  3715. );
  3716. clean_term_cache( (int) $child_tt_id, '', false );
  3717. }
  3718. } else {
  3719. // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
  3720. clean_term_cache( $new_term_id, $term_taxonomy->taxonomy, false );
  3721. }
  3722. clean_term_cache( $term_id, $term_taxonomy->taxonomy, false );
  3723. /*
  3724. * Taxonomy cache clearing is delayed to avoid race conditions that may occur when
  3725. * regenerating the taxonomy's hierarchy tree.
  3726. */
  3727. $taxonomies_to_clean = array( $term_taxonomy->taxonomy );
  3728. // Clean the cache for term taxonomies formerly shared with the current term.
  3729. $shared_term_taxonomies = $wpdb->get_col( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
  3730. $taxonomies_to_clean = array_merge( $taxonomies_to_clean, $shared_term_taxonomies );
  3731. foreach ( $taxonomies_to_clean as $taxonomy_to_clean ) {
  3732. clean_taxonomy_cache( $taxonomy_to_clean );
  3733. }
  3734. // Keep a record of term_ids that have been split, keyed by old term_id. See wp_get_split_term().
  3735. if ( $record ) {
  3736. $split_term_data = get_option( '_split_terms', array() );
  3737. if ( ! isset( $split_term_data[ $term_id ] ) ) {
  3738. $split_term_data[ $term_id ] = array();
  3739. }
  3740. $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
  3741. update_option( '_split_terms', $split_term_data );
  3742. }
  3743. // If we've just split the final shared term, set the "finished" flag.
  3744. $shared_terms_exist = $wpdb->get_results(
  3745. "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
  3746. LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
  3747. GROUP BY t.term_id
  3748. HAVING term_tt_count > 1
  3749. LIMIT 1"
  3750. );
  3751. if ( ! $shared_terms_exist ) {
  3752. update_option( 'finished_splitting_shared_terms', true );
  3753. }
  3754. /**
  3755. * Fires after a previously shared taxonomy term is split into two separate terms.
  3756. *
  3757. * @since 4.2.0
  3758. *
  3759. * @param int $term_id ID of the formerly shared term.
  3760. * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
  3761. * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
  3762. * @param string $taxonomy Taxonomy for the split term.
  3763. */
  3764. do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
  3765. return $new_term_id;
  3766. }
  3767. /**
  3768. * Splits a batch of shared taxonomy terms.
  3769. *
  3770. * @since 4.3.0
  3771. *
  3772. * @global wpdb $wpdb WordPress database abstraction object.
  3773. */
  3774. function _wp_batch_split_terms() {
  3775. global $wpdb;
  3776. $lock_name = 'term_split.lock';
  3777. // Try to lock.
  3778. $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
  3779. if ( ! $lock_result ) {
  3780. $lock_result = get_option( $lock_name );
  3781. // Bail if we were unable to create a lock, or if the existing lock is still valid.
  3782. if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
  3783. wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
  3784. return;
  3785. }
  3786. }
  3787. // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
  3788. update_option( $lock_name, time() );
  3789. // Get a list of shared terms (those with more than one associated row in term_taxonomy).
  3790. $shared_terms = $wpdb->get_results(
  3791. "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
  3792. LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
  3793. GROUP BY t.term_id
  3794. HAVING term_tt_count > 1
  3795. LIMIT 10"
  3796. );
  3797. // No more terms, we're done here.
  3798. if ( ! $shared_terms ) {
  3799. update_option( 'finished_splitting_shared_terms', true );
  3800. delete_option( $lock_name );
  3801. return;
  3802. }
  3803. // Shared terms found? We'll need to run this script again.
  3804. wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
  3805. // Rekey shared term array for faster lookups.
  3806. $_shared_terms = array();
  3807. foreach ( $shared_terms as $shared_term ) {
  3808. $term_id = (int) $shared_term->term_id;
  3809. $_shared_terms[ $term_id ] = $shared_term;
  3810. }
  3811. $shared_terms = $_shared_terms;
  3812. // Get term taxonomy data for all shared terms.
  3813. $shared_term_ids = implode( ',', array_keys( $shared_terms ) );
  3814. $shared_tts = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" );
  3815. // Split term data recording is slow, so we do it just once, outside the loop.
  3816. $split_term_data = get_option( '_split_terms', array() );
  3817. $skipped_first_term = array();
  3818. $taxonomies = array();
  3819. foreach ( $shared_tts as $shared_tt ) {
  3820. $term_id = (int) $shared_tt->term_id;
  3821. // Don't split the first tt belonging to a given term_id.
  3822. if ( ! isset( $skipped_first_term[ $term_id ] ) ) {
  3823. $skipped_first_term[ $term_id ] = 1;
  3824. continue;
  3825. }
  3826. if ( ! isset( $split_term_data[ $term_id ] ) ) {
  3827. $split_term_data[ $term_id ] = array();
  3828. }
  3829. // Keep track of taxonomies whose hierarchies need flushing.
  3830. if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) {
  3831. $taxonomies[ $shared_tt->taxonomy ] = 1;
  3832. }
  3833. // Split the term.
  3834. $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false );
  3835. }
  3836. // Rebuild the cached hierarchy for each affected taxonomy.
  3837. foreach ( array_keys( $taxonomies ) as $tax ) {
  3838. delete_option( "{$tax}_children" );
  3839. _get_term_hierarchy( $tax );
  3840. }
  3841. update_option( '_split_terms', $split_term_data );
  3842. delete_option( $lock_name );
  3843. }
  3844. /**
  3845. * In order to avoid the _wp_batch_split_terms() job being accidentally removed,
  3846. * checks that it's still scheduled while we haven't finished splitting terms.
  3847. *
  3848. * @ignore
  3849. * @since 4.3.0
  3850. */
  3851. function _wp_check_for_scheduled_split_terms() {
  3852. if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) {
  3853. wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' );
  3854. }
  3855. }
  3856. /**
  3857. * Checks default categories when a term gets split to see if any of them need to be updated.
  3858. *
  3859. * @ignore
  3860. * @since 4.2.0
  3861. *
  3862. * @param int $term_id ID of the formerly shared term.
  3863. * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
  3864. * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
  3865. * @param string $taxonomy Taxonomy for the split term.
  3866. */
  3867. function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
  3868. if ( 'category' !== $taxonomy ) {
  3869. return;
  3870. }
  3871. foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
  3872. if ( (int) get_option( $option, -1 ) === $term_id ) {
  3873. update_option( $option, $new_term_id );
  3874. }
  3875. }
  3876. }
  3877. /**
  3878. * Checks menu items when a term gets split to see if any of them need to be updated.
  3879. *
  3880. * @ignore
  3881. * @since 4.2.0
  3882. *
  3883. * @global wpdb $wpdb WordPress database abstraction object.
  3884. *
  3885. * @param int $term_id ID of the formerly shared term.
  3886. * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
  3887. * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
  3888. * @param string $taxonomy Taxonomy for the split term.
  3889. */
  3890. function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
  3891. global $wpdb;
  3892. $post_ids = $wpdb->get_col(
  3893. $wpdb->prepare(
  3894. "SELECT m1.post_id
  3895. FROM {$wpdb->postmeta} AS m1
  3896. INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
  3897. INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
  3898. WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
  3899. AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = %s )
  3900. AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
  3901. $taxonomy,
  3902. $term_id
  3903. )
  3904. );
  3905. if ( $post_ids ) {
  3906. foreach ( $post_ids as $post_id ) {
  3907. update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
  3908. }
  3909. }
  3910. }
  3911. /**
  3912. * If the term being split is a nav_menu, changes associations.
  3913. *
  3914. * @ignore
  3915. * @since 4.3.0
  3916. *
  3917. * @param int $term_id ID of the formerly shared term.
  3918. * @param int $new_term_id ID of the new term created for the $term_taxonomy_id.
  3919. * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split.
  3920. * @param string $taxonomy Taxonomy for the split term.
  3921. */
  3922. function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
  3923. if ( 'nav_menu' !== $taxonomy ) {
  3924. return;
  3925. }
  3926. // Update menu locations.
  3927. $locations = get_nav_menu_locations();
  3928. foreach ( $locations as $location => $menu_id ) {
  3929. if ( $term_id === $menu_id ) {
  3930. $locations[ $location ] = $new_term_id;
  3931. }
  3932. }
  3933. set_theme_mod( 'nav_menu_locations', $locations );
  3934. }
  3935. /**
  3936. * Gets data about terms that previously shared a single term_id, but have since been split.
  3937. *
  3938. * @since 4.2.0
  3939. *
  3940. * @param int $old_term_id Term ID. This is the old, pre-split term ID.
  3941. * @return array Array of new term IDs, keyed by taxonomy.
  3942. */
  3943. function wp_get_split_terms( $old_term_id ) {
  3944. $split_terms = get_option( '_split_terms', array() );
  3945. $terms = array();
  3946. if ( isset( $split_terms[ $old_term_id ] ) ) {
  3947. $terms = $split_terms[ $old_term_id ];
  3948. }
  3949. return $terms;
  3950. }
  3951. /**
  3952. * Gets the new term ID corresponding to a previously split term.
  3953. *
  3954. * @since 4.2.0
  3955. *
  3956. * @param int $old_term_id Term ID. This is the old, pre-split term ID.
  3957. * @param string $taxonomy Taxonomy that the term belongs to.
  3958. * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy,
  3959. * the new term_id will be returned. If no previously split term is found matching
  3960. * the parameters, returns false.
  3961. */
  3962. function wp_get_split_term( $old_term_id, $taxonomy ) {
  3963. $split_terms = wp_get_split_terms( $old_term_id );
  3964. $term_id = false;
  3965. if ( isset( $split_terms[ $taxonomy ] ) ) {
  3966. $term_id = (int) $split_terms[ $taxonomy ];
  3967. }
  3968. return $term_id;
  3969. }
  3970. /**
  3971. * Determines whether a term is shared between multiple taxonomies.
  3972. *
  3973. * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or
  3974. * other delays in upgrade routines may cause shared terms to remain.
  3975. *
  3976. * @since 4.4.0
  3977. *
  3978. * @param int $term_id Term ID.
  3979. * @return bool Returns false if a term is not shared between multiple taxonomies or
  3980. * if splitting shared taxonomy terms is finished.
  3981. */
  3982. function wp_term_is_shared( $term_id ) {
  3983. global $wpdb;
  3984. if ( get_option( 'finished_splitting_shared_terms' ) ) {
  3985. return false;
  3986. }
  3987. $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
  3988. return $tt_count > 1;
  3989. }
  3990. /**
  3991. * Generates a permalink for a taxonomy term archive.
  3992. *
  3993. * @since 2.5.0
  3994. *
  3995. * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  3996. *
  3997. * @param WP_Term|int|string $term The term object, ID, or slug whose link will be retrieved.
  3998. * @param string $taxonomy Optional. Taxonomy. Default empty.
  3999. * @return string|WP_Error URL of the taxonomy term archive on success, WP_Error if term does not exist.
  4000. */
  4001. function get_term_link( $term, $taxonomy = '' ) {
  4002. global $wp_rewrite;
  4003. if ( ! is_object( $term ) ) {
  4004. if ( is_int( $term ) ) {
  4005. $term = get_term( $term, $taxonomy );
  4006. } else {
  4007. $term = get_term_by( 'slug', $term, $taxonomy );
  4008. }
  4009. }
  4010. if ( ! is_object( $term ) ) {
  4011. $term = new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
  4012. }
  4013. if ( is_wp_error( $term ) ) {
  4014. return $term;
  4015. }
  4016. $taxonomy = $term->taxonomy;
  4017. $termlink = $wp_rewrite->get_extra_permastruct( $taxonomy );
  4018. /**
  4019. * Filters the permalink structure for a term before token replacement occurs.
  4020. *
  4021. * @since 4.9.0
  4022. *
  4023. * @param string $termlink The permalink structure for the term's taxonomy.
  4024. * @param WP_Term $term The term object.
  4025. */
  4026. $termlink = apply_filters( 'pre_term_link', $termlink, $term );
  4027. $slug = $term->slug;
  4028. $t = get_taxonomy( $taxonomy );
  4029. if ( empty( $termlink ) ) {
  4030. if ( 'category' === $taxonomy ) {
  4031. $termlink = '?cat=' . $term->term_id;
  4032. } elseif ( $t->query_var ) {
  4033. $termlink = "?$t->query_var=$slug";
  4034. } else {
  4035. $termlink = "?taxonomy=$taxonomy&term=$slug";
  4036. }
  4037. $termlink = home_url( $termlink );
  4038. } else {
  4039. if ( ! empty( $t->rewrite['hierarchical'] ) ) {
  4040. $hierarchical_slugs = array();
  4041. $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
  4042. foreach ( (array) $ancestors as $ancestor ) {
  4043. $ancestor_term = get_term( $ancestor, $taxonomy );
  4044. $hierarchical_slugs[] = $ancestor_term->slug;
  4045. }
  4046. $hierarchical_slugs = array_reverse( $hierarchical_slugs );
  4047. $hierarchical_slugs[] = $slug;
  4048. $termlink = str_replace( "%$taxonomy%", implode( '/', $hierarchical_slugs ), $termlink );
  4049. } else {
  4050. $termlink = str_replace( "%$taxonomy%", $slug, $termlink );
  4051. }
  4052. $termlink = home_url( user_trailingslashit( $termlink, 'category' ) );
  4053. }
  4054. // Back compat filters.
  4055. if ( 'post_tag' === $taxonomy ) {
  4056. /**
  4057. * Filters the tag link.
  4058. *
  4059. * @since 2.3.0
  4060. * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter.
  4061. * @since 5.4.1 Restored (un-deprecated).
  4062. *
  4063. * @param string $termlink Tag link URL.
  4064. * @param int $term_id Term ID.
  4065. */
  4066. $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
  4067. } elseif ( 'category' === $taxonomy ) {
  4068. /**
  4069. * Filters the category link.
  4070. *
  4071. * @since 1.5.0
  4072. * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter.
  4073. * @since 5.4.1 Restored (un-deprecated).
  4074. *
  4075. * @param string $termlink Category link URL.
  4076. * @param int $term_id Term ID.
  4077. */
  4078. $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
  4079. }
  4080. /**
  4081. * Filters the term link.
  4082. *
  4083. * @since 2.5.0
  4084. *
  4085. * @param string $termlink Term link URL.
  4086. * @param WP_Term $term Term object.
  4087. * @param string $taxonomy Taxonomy slug.
  4088. */
  4089. return apply_filters( 'term_link', $termlink, $term, $taxonomy );
  4090. }
  4091. /**
  4092. * Displays the taxonomies of a post with available options.
  4093. *
  4094. * This function can be used within the loop to display the taxonomies for a
  4095. * post without specifying the Post ID. You can also use it outside the Loop to
  4096. * display the taxonomies for a specific post.
  4097. *
  4098. * @since 2.5.0
  4099. *
  4100. * @param array $args {
  4101. * Arguments about which post to use and how to format the output. Shares all of the arguments
  4102. * supported by get_the_taxonomies(), in addition to the following.
  4103. *
  4104. * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post.
  4105. * @type string $before Displays before the taxonomies. Default empty string.
  4106. * @type string $sep Separates each taxonomy. Default is a space.
  4107. * @type string $after Displays after the taxonomies. Default empty string.
  4108. * }
  4109. */
  4110. function the_taxonomies( $args = array() ) {
  4111. $defaults = array(
  4112. 'post' => 0,
  4113. 'before' => '',
  4114. 'sep' => ' ',
  4115. 'after' => '',
  4116. );
  4117. $parsed_args = wp_parse_args( $args, $defaults );
  4118. echo $parsed_args['before'] . implode( $parsed_args['sep'], get_the_taxonomies( $parsed_args['post'], $parsed_args ) ) . $parsed_args['after'];
  4119. }
  4120. /**
  4121. * Retrieves all taxonomies associated with a post.
  4122. *
  4123. * This function can be used within the loop. It will also return an array of
  4124. * the taxonomies with links to the taxonomy and name.
  4125. *
  4126. * @since 2.5.0
  4127. *
  4128. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  4129. * @param array $args {
  4130. * Optional. Arguments about how to format the list of taxonomies. Default empty array.
  4131. *
  4132. * @type string $template Template for displaying a taxonomy label and list of terms.
  4133. * Default is "Label: Terms."
  4134. * @type string $term_template Template for displaying a single term in the list. Default is the term name
  4135. * linked to its archive.
  4136. * }
  4137. * @return string[] List of taxonomies.
  4138. */
  4139. function get_the_taxonomies( $post = 0, $args = array() ) {
  4140. $post = get_post( $post );
  4141. $args = wp_parse_args(
  4142. $args,
  4143. array(
  4144. /* translators: %s: Taxonomy label, %l: List of terms formatted as per $term_template. */
  4145. 'template' => __( '%s: %l.' ),
  4146. 'term_template' => '<a href="%1$s">%2$s</a>',
  4147. )
  4148. );
  4149. $taxonomies = array();
  4150. if ( ! $post ) {
  4151. return $taxonomies;
  4152. }
  4153. foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
  4154. $t = (array) get_taxonomy( $taxonomy );
  4155. if ( empty( $t['label'] ) ) {
  4156. $t['label'] = $taxonomy;
  4157. }
  4158. if ( empty( $t['args'] ) ) {
  4159. $t['args'] = array();
  4160. }
  4161. if ( empty( $t['template'] ) ) {
  4162. $t['template'] = $args['template'];
  4163. }
  4164. if ( empty( $t['term_template'] ) ) {
  4165. $t['term_template'] = $args['term_template'];
  4166. }
  4167. $terms = get_object_term_cache( $post->ID, $taxonomy );
  4168. if ( false === $terms ) {
  4169. $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
  4170. }
  4171. $links = array();
  4172. foreach ( $terms as $term ) {
  4173. $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
  4174. }
  4175. if ( $links ) {
  4176. $taxonomies[ $taxonomy ] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
  4177. }
  4178. }
  4179. return $taxonomies;
  4180. }
  4181. /**
  4182. * Retrieves all taxonomy names for the given post.
  4183. *
  4184. * @since 2.5.0
  4185. *
  4186. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  4187. * @return string[] An array of all taxonomy names for the given post.
  4188. */
  4189. function get_post_taxonomies( $post = 0 ) {
  4190. $post = get_post( $post );
  4191. return get_object_taxonomies( $post );
  4192. }
  4193. /**
  4194. * Determines if the given object is associated with any of the given terms.
  4195. *
  4196. * The given terms are checked against the object's terms' term_ids, names and slugs.
  4197. * Terms given as integers will only be checked against the object's terms' term_ids.
  4198. * If no terms are given, determines if object is associated with any terms in the given taxonomy.
  4199. *
  4200. * @since 2.7.0
  4201. *
  4202. * @param int $object_id ID of the object (post ID, link ID, ...).
  4203. * @param string $taxonomy Single taxonomy name.
  4204. * @param int|string|int[]|string[] $terms Optional. Term ID, name, slug, or array of such
  4205. * to check against. Default null.
  4206. * @return bool|WP_Error WP_Error on input error.
  4207. */
  4208. function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
  4209. $object_id = (int) $object_id;
  4210. if ( ! $object_id ) {
  4211. return new WP_Error( 'invalid_object', __( 'Invalid object ID.' ) );
  4212. }
  4213. $object_terms = get_object_term_cache( $object_id, $taxonomy );
  4214. if ( false === $object_terms ) {
  4215. $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
  4216. if ( is_wp_error( $object_terms ) ) {
  4217. return $object_terms;
  4218. }
  4219. wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
  4220. }
  4221. if ( is_wp_error( $object_terms ) ) {
  4222. return $object_terms;
  4223. }
  4224. if ( empty( $object_terms ) ) {
  4225. return false;
  4226. }
  4227. if ( empty( $terms ) ) {
  4228. return ( ! empty( $object_terms ) );
  4229. }
  4230. $terms = (array) $terms;
  4231. $ints = array_filter( $terms, 'is_int' );
  4232. if ( $ints ) {
  4233. $strs = array_diff( $terms, $ints );
  4234. } else {
  4235. $strs =& $terms;
  4236. }
  4237. foreach ( $object_terms as $object_term ) {
  4238. // If term is an int, check against term_ids only.
  4239. if ( $ints && in_array( $object_term->term_id, $ints, true ) ) {
  4240. return true;
  4241. }
  4242. if ( $strs ) {
  4243. // Only check numeric strings against term_id, to avoid false matches due to type juggling.
  4244. $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
  4245. if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
  4246. return true;
  4247. }
  4248. if ( in_array( $object_term->name, $strs, true ) ) {
  4249. return true;
  4250. }
  4251. if ( in_array( $object_term->slug, $strs, true ) ) {
  4252. return true;
  4253. }
  4254. }
  4255. }
  4256. return false;
  4257. }
  4258. /**
  4259. * Determines if the given object type is associated with the given taxonomy.
  4260. *
  4261. * @since 3.0.0
  4262. *
  4263. * @param string $object_type Object type string.
  4264. * @param string $taxonomy Single taxonomy name.
  4265. * @return bool True if object is associated with the taxonomy, otherwise false.
  4266. */
  4267. function is_object_in_taxonomy( $object_type, $taxonomy ) {
  4268. $taxonomies = get_object_taxonomies( $object_type );
  4269. if ( empty( $taxonomies ) ) {
  4270. return false;
  4271. }
  4272. return in_array( $taxonomy, $taxonomies, true );
  4273. }
  4274. /**
  4275. * Gets an array of ancestor IDs for a given object.
  4276. *
  4277. * @since 3.1.0
  4278. * @since 4.1.0 Introduced the `$resource_type` argument.
  4279. *
  4280. * @param int $object_id Optional. The ID of the object. Default 0.
  4281. * @param string $object_type Optional. The type of object for which we'll be retrieving
  4282. * ancestors. Accepts a post type or a taxonomy name. Default empty.
  4283. * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
  4284. * or 'taxonomy'. Default empty.
  4285. * @return int[] An array of IDs of ancestors from lowest to highest in the hierarchy.
  4286. */
  4287. function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
  4288. $object_id = (int) $object_id;
  4289. $ancestors = array();
  4290. if ( empty( $object_id ) ) {
  4291. /** This filter is documented in wp-includes/taxonomy.php */
  4292. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
  4293. }
  4294. if ( ! $resource_type ) {
  4295. if ( is_taxonomy_hierarchical( $object_type ) ) {
  4296. $resource_type = 'taxonomy';
  4297. } elseif ( post_type_exists( $object_type ) ) {
  4298. $resource_type = 'post_type';
  4299. }
  4300. }
  4301. if ( 'taxonomy' === $resource_type ) {
  4302. $term = get_term( $object_id, $object_type );
  4303. while ( ! is_wp_error( $term ) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors, true ) ) {
  4304. $ancestors[] = (int) $term->parent;
  4305. $term = get_term( $term->parent, $object_type );
  4306. }
  4307. } elseif ( 'post_type' === $resource_type ) {
  4308. $ancestors = get_post_ancestors( $object_id );
  4309. }
  4310. /**
  4311. * Filters a given object's ancestors.
  4312. *
  4313. * @since 3.1.0
  4314. * @since 4.1.1 Introduced the `$resource_type` parameter.
  4315. *
  4316. * @param int[] $ancestors An array of IDs of object ancestors.
  4317. * @param int $object_id Object ID.
  4318. * @param string $object_type Type of object.
  4319. * @param string $resource_type Type of resource $object_type is.
  4320. */
  4321. return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
  4322. }
  4323. /**
  4324. * Returns the term's parent's term ID.
  4325. *
  4326. * @since 3.1.0
  4327. *
  4328. * @param int $term_id Term ID.
  4329. * @param string $taxonomy Taxonomy name.
  4330. * @return int|false Parent term ID on success, false on failure.
  4331. */
  4332. function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
  4333. $term = get_term( $term_id, $taxonomy );
  4334. if ( ! $term || is_wp_error( $term ) ) {
  4335. return false;
  4336. }
  4337. return (int) $term->parent;
  4338. }
  4339. /**
  4340. * Checks the given subset of the term hierarchy for hierarchy loops.
  4341. * Prevents loops from forming and breaks those that it finds.
  4342. *
  4343. * Attached to the {@see 'wp_update_term_parent'} filter.
  4344. *
  4345. * @since 3.1.0
  4346. *
  4347. * @param int $parent `term_id` of the parent for the term we're checking.
  4348. * @param int $term_id The term we're checking.
  4349. * @param string $taxonomy The taxonomy of the term we're checking.
  4350. * @return int The new parent for the term.
  4351. */
  4352. function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
  4353. // Nothing fancy here - bail.
  4354. if ( ! $parent ) {
  4355. return 0;
  4356. }
  4357. // Can't be its own parent.
  4358. if ( $parent === $term_id ) {
  4359. return 0;
  4360. }
  4361. // Now look for larger loops.
  4362. $loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) );
  4363. if ( ! $loop ) {
  4364. return $parent; // No loop.
  4365. }
  4366. // Setting $parent to the given value causes a loop.
  4367. if ( isset( $loop[ $term_id ] ) ) {
  4368. return 0;
  4369. }
  4370. // There's a loop, but it doesn't contain $term_id. Break the loop.
  4371. foreach ( array_keys( $loop ) as $loop_member ) {
  4372. wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
  4373. }
  4374. return $parent;
  4375. }
  4376. /**
  4377. * Determines whether a taxonomy is considered "viewable".
  4378. *
  4379. * @since 5.1.0
  4380. *
  4381. * @param string|WP_Taxonomy $taxonomy Taxonomy name or object.
  4382. * @return bool Whether the taxonomy should be considered viewable.
  4383. */
  4384. function is_taxonomy_viewable( $taxonomy ) {
  4385. if ( is_scalar( $taxonomy ) ) {
  4386. $taxonomy = get_taxonomy( $taxonomy );
  4387. if ( ! $taxonomy ) {
  4388. return false;
  4389. }
  4390. }
  4391. return $taxonomy->publicly_queryable;
  4392. }
  4393. /**
  4394. * Determines whether a term is publicly viewable.
  4395. *
  4396. * A term is considered publicly viewable if its taxonomy is viewable.
  4397. *
  4398. * @since 6.1.0
  4399. *
  4400. * @param int|WP_Term $term Term ID or term object.
  4401. * @return bool Whether the term is publicly viewable.
  4402. */
  4403. function is_term_publicly_viewable( $term ) {
  4404. $term = get_term( $term );
  4405. if ( ! $term ) {
  4406. return false;
  4407. }
  4408. return is_taxonomy_viewable( $term->taxonomy );
  4409. }
  4410. /**
  4411. * Sets the last changed time for the 'terms' cache group.
  4412. *
  4413. * @since 5.0.0
  4414. */
  4415. function wp_cache_set_terms_last_changed() {
  4416. wp_cache_set( 'last_changed', microtime(), 'terms' );
  4417. }
  4418. /**
  4419. * Aborts calls to term meta if it is not supported.
  4420. *
  4421. * @since 5.0.0
  4422. *
  4423. * @param mixed $check Skip-value for whether to proceed term meta function execution.
  4424. * @return mixed Original value of $check, or false if term meta is not supported.
  4425. */
  4426. function wp_check_term_meta_support_prefilter( $check ) {
  4427. if ( get_option( 'db_version' ) < 34370 ) {
  4428. return false;
  4429. }
  4430. return $check;
  4431. }