Keine Beschreibung

taxonomy.php 164KB

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