taxonomy.php 147 KB

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