No Description

taxonomy.php 165KB

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