[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> category.php (source)

   1  <?php
   2  /**
   3   * Taxonomy API: Core category-specific functionality
   4   *
   5   * @package WordPress
   6   * @subpackage Taxonomy
   7   */
   8  
   9  /**
  10   * Retrieves a list of category objects.
  11   *
  12   * If you set the 'taxonomy' argument to 'link_category', the link categories
  13   * will be returned instead.
  14   *
  15   * @since 2.1.0
  16   *
  17   * @see get_terms() Type of arguments that can be changed.
  18   *
  19   * @param string|array $args {
  20   *     Optional. Arguments to retrieve categories. See get_terms() for additional options.
  21   *
  22   *     @type string $taxonomy Taxonomy to retrieve terms for. Default 'category'.
  23   * }
  24   * @return array List of category objects.
  25   *
  26   * @phpstan-return (
  27   *     $args is array{ fields: 'count', ... }
  28   *         ? list<0|numeric-string>
  29   *         : (
  30   *             $args is array{ fields: 'names'|'slugs', ... }
  31   *                 ? list<string>
  32   *                 : (
  33   *                     $args is array{ fields: 'id=>name'|'id=>slug', ... }
  34   *                         ? array<int, string>
  35   *                         : (
  36   *                             $args is array{ fields: 'id=>parent', ... }
  37   *                                 ? array<int, int>
  38   *                                 : ( $args is array{ fields: 'ids'|'tt_ids', ... } ? list<int> : array<int, WP_Term> )
  39   *                         )
  40   *                 )
  41   *         )
  42   * )
  43   */
  44  function get_categories( $args = '' ) {
  45      $defaults = array( 'taxonomy' => 'category' );
  46      $args     = wp_parse_args( $args, $defaults );
  47  
  48      /**
  49       * Filters the taxonomy used to retrieve terms when calling get_categories().
  50       *
  51       * @since 2.7.0
  52       *
  53       * @param string $taxonomy Taxonomy to retrieve terms from.
  54       * @param array  $args     An array of arguments. See get_terms().
  55       */
  56      $args['taxonomy'] = apply_filters( 'get_categories_taxonomy', $args['taxonomy'], $args );
  57  
  58      // Back compat.
  59      if ( isset( $args['type'] ) && 'link' === $args['type'] ) {
  60          _deprecated_argument(
  61              __FUNCTION__,
  62              '3.0.0',
  63              sprintf(
  64                  /* translators: 1: "type => link", 2: "taxonomy => link_category" */
  65                  __( '%1$s is deprecated. Use %2$s instead.' ),
  66                  '<code>type => link</code>',
  67                  '<code>taxonomy => link_category</code>'
  68              )
  69          );
  70          $args['taxonomy'] = 'link_category';
  71      }
  72  
  73      $categories = get_terms( $args );
  74  
  75      if ( is_wp_error( $categories ) ) {
  76          $categories = array();
  77      } else {
  78          $categories = (array) $categories;
  79          foreach ( array_keys( $categories ) as $k ) {
  80              _make_cat_compat( $categories[ $k ] );
  81          }
  82      }
  83  
  84      return $categories;
  85  }
  86  
  87  /**
  88   * Retrieves category data given a category ID or category object.
  89   *
  90   * If you pass the $category parameter an object, which is assumed to be the
  91   * category row object retrieved the database. It will cache the category data.
  92   *
  93   * If you pass $category an integer of the category ID, then that category will
  94   * be retrieved from the database, if it isn't already cached, and pass it back.
  95   *
  96   * If you look at get_term(), then both types will be passed through several
  97   * filters and finally sanitized based on the $filter parameter value.
  98   *
  99   * @since 1.5.1
 100   *
 101   * @param int|object $category Category ID or category row object.
 102   * @param string     $output   Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 103   *                             correspond to a WP_Term object, an associative array, or a numeric array,
 104   *                             respectively. Default OBJECT.
 105   * @param string     $filter   Optional. How to sanitize category fields. Default 'raw'.
 106   * @return WP_Term|array|WP_Error|null Category data in type defined by $output parameter.
 107   *                                     Returns a WP_Term object with backwards compatible property aliases filled in.
 108   *                                     WP_Error if $category is empty, null if it does not exist.
 109   *
 110   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
 111   * @phpstan-return (
 112   *     $output is 'ARRAY_A' ? array<string, mixed>|WP_Error|null : (
 113   *         $output is 'ARRAY_N' ? list<mixed>|WP_Error|null : WP_Term|WP_Error|null
 114   *     )
 115   * )
 116   */
 117  function get_category( $category, $output = OBJECT, $filter = 'raw' ) {
 118      $category = get_term( $category, 'category', $output, $filter );
 119  
 120      if ( is_wp_error( $category ) ) {
 121          return $category;
 122      }
 123  
 124      _make_cat_compat( $category );
 125  
 126      return $category;
 127  }
 128  
 129  /**
 130   * Retrieves a category based on URL containing the category slug.
 131   *
 132   * Breaks the $category_path parameter up to get the category slug.
 133   *
 134   * Tries to find the child path and will return it. If it doesn't find a
 135   * match, then it will return the first category matching slug, if $full_match,
 136   * is set to false. If it does not, then it will return null.
 137   *
 138   * It is also possible that it will return a WP_Error object on failure. Check
 139   * for it when using this function.
 140   *
 141   * @since 2.1.0
 142   *
 143   * @param string $category_path URL containing category slugs.
 144   * @param bool   $full_match    Optional. Whether full path should be matched.
 145   * @param string $output        Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 146   *                              correspond to a WP_Term object, an associative array, or a numeric array,
 147   *                              respectively. Default OBJECT.
 148   * @return WP_Term|array|WP_Error|null Type is based on $output value.
 149   *
 150   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
 151   * @phpstan-return (
 152   *     $output is 'ARRAY_A' ? array<string, mixed>|WP_Error|null : (
 153   *         $output is 'ARRAY_N' ? list<mixed>|WP_Error|null : WP_Term|WP_Error|null
 154   *     )
 155   * )
 156   */
 157  function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) {
 158      $category_path  = rawurlencode( urldecode( $category_path ) );
 159      $category_path  = str_replace( '%2F', '/', $category_path );
 160      $category_path  = str_replace( '%20', ' ', $category_path );
 161      $category_paths = '/' . trim( $category_path, '/' );
 162      $leaf_path      = sanitize_title( basename( $category_paths ) );
 163      $category_paths = explode( '/', $category_paths );
 164      $full_path      = '';
 165  
 166      foreach ( (array) $category_paths as $pathdir ) {
 167          $full_path .= ( '' !== $pathdir ? '/' : '' ) . sanitize_title( $pathdir );
 168      }
 169  
 170      $categories = get_terms(
 171          array(
 172              'taxonomy' => 'category',
 173              'get'      => 'all',
 174              'slug'     => $leaf_path,
 175          )
 176      );
 177  
 178      if ( empty( $categories ) ) {
 179          return null;
 180      }
 181  
 182      foreach ( $categories as $category ) {
 183          $path        = '/' . $leaf_path;
 184          $curcategory = $category;
 185  
 186          while ( ( 0 !== $curcategory->parent ) && ( $curcategory->parent !== $curcategory->term_id ) ) {
 187              $curcategory = get_term( $curcategory->parent, 'category' );
 188  
 189              if ( is_wp_error( $curcategory ) ) {
 190                  return $curcategory;
 191              }
 192  
 193              $path = '/' . $curcategory->slug . $path;
 194          }
 195  
 196          if ( $path === $full_path ) {
 197              $category = get_term( $category->term_id, 'category', $output );
 198              _make_cat_compat( $category );
 199  
 200              return $category;
 201          }
 202      }
 203  
 204      // If full matching is not required, return the first cat that matches the leaf.
 205      if ( ! $full_match ) {
 206          $category = get_term( reset( $categories )->term_id, 'category', $output );
 207          _make_cat_compat( $category );
 208  
 209          return $category;
 210      }
 211  
 212      return null;
 213  }
 214  
 215  /**
 216   * Retrieves a category object by category slug.
 217   *
 218   * @since 2.3.0
 219   *
 220   * @param string $slug The category slug.
 221   * @return object|false Category data object on success, false if not found.
 222   */
 223  function get_category_by_slug( $slug ) {
 224      $category = get_term_by( 'slug', $slug, 'category' );
 225  
 226      if ( $category ) {
 227          _make_cat_compat( $category );
 228      }
 229  
 230      return $category;
 231  }
 232  
 233  /**
 234   * Retrieves the ID of a category from its name.
 235   *
 236   * @since 1.0.0
 237   *
 238   * @param string $cat_name Category name.
 239   * @return int Category ID on success, 0 if the category doesn't exist.
 240   */
 241  function get_cat_ID( $cat_name ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
 242      $cat = get_term_by( 'name', $cat_name, 'category' );
 243  
 244      if ( $cat ) {
 245          return $cat->term_id;
 246      }
 247  
 248      return 0;
 249  }
 250  
 251  /**
 252   * Retrieves the name of a category from its ID.
 253   *
 254   * @since 1.0.0
 255   *
 256   * @param int $cat_id Category ID.
 257   * @return string Category name, or an empty string if the category doesn't exist.
 258   */
 259  function get_cat_name( $cat_id ) {
 260      $cat_id   = (int) $cat_id;
 261      $category = get_term( $cat_id, 'category' );
 262  
 263      if ( ! $category || is_wp_error( $category ) ) {
 264          return '';
 265      }
 266  
 267      return $category->name;
 268  }
 269  
 270  /**
 271   * Checks if a category is an ancestor of another category.
 272   *
 273   * You can use either an ID or the category object for both parameters.
 274   * If you use an integer, the category will be retrieved.
 275   *
 276   * @since 2.1.0
 277   *
 278   * @param int|object $cat1 ID or object to check if this is the parent category.
 279   * @param int|object $cat2 The child category.
 280   * @return bool Whether $cat2 is child of $cat1.
 281   */
 282  function cat_is_ancestor_of( $cat1, $cat2 ) {
 283      return term_is_ancestor_of( $cat1, $cat2, 'category' );
 284  }
 285  
 286  /**
 287   * Sanitizes category data based on context.
 288   *
 289   * @since 2.3.0
 290   *
 291   * @param object|array $category Category data.
 292   * @param string       $context  Optional. Default 'display'.
 293   * @return object|array Same type as $category with sanitized data for safe use.
 294   */
 295  function sanitize_category( $category, $context = 'display' ) {
 296      return sanitize_term( $category, 'category', $context );
 297  }
 298  
 299  /**
 300   * Sanitizes data in single category key field.
 301   *
 302   * @since 2.3.0
 303   *
 304   * @param string $field   Category key to sanitize.
 305   * @param mixed  $value   Category value to sanitize.
 306   * @param int    $cat_id  Category ID.
 307   * @param string $context What filter to use, 'raw', 'display', etc.
 308   * @return mixed Value after $value has been sanitized.
 309   */
 310  function sanitize_category_field( $field, $value, $cat_id, $context ) {
 311      return sanitize_term_field( $field, $value, $cat_id, 'category', $context );
 312  }
 313  
 314  /* Tags */
 315  
 316  /**
 317   * Retrieves all post tags.
 318   *
 319   * @since 2.3.0
 320   *
 321   * @param string|array $args {
 322   *     Optional. Arguments to retrieve tags. See get_terms() for additional options.
 323   *
 324   *     @type string $taxonomy Taxonomy to retrieve terms for. Default 'post_tag'.
 325   * }
 326   * @return WP_Term[]|int|WP_Error Array of 'post_tag' term objects, a count thereof,
 327   *                                or WP_Error if any of the taxonomies do not exist.
 328   *
 329   * @phpstan-return (
 330   *     $args is array{ fields: 'names'|'slugs', ... }
 331   *         ? list<string>
 332   *         : (
 333   *             $args is array{ fields: 'id=>name'|'id=>slug', ... }
 334   *                 ? array<int, string>
 335   *                 : (
 336   *                     $args is array{ fields: 'id=>parent', ... }
 337   *                         ? array<int, int>
 338   *                         : ( $args is array{ fields: 'ids'|'tt_ids', ... } ? list<int> : array<int, WP_Term> )
 339   *                 )
 340   *         )
 341   * )|WP_Error
 342   */
 343  function get_tags( $args = '' ) {
 344      $defaults = array( 'taxonomy' => 'post_tag' );
 345      $args     = wp_parse_args( $args, $defaults );
 346  
 347      $tags = get_terms( $args );
 348  
 349      if ( empty( $tags ) ) {
 350          $tags = array();
 351      } else {
 352          /**
 353           * Filters the array of term objects returned for the 'post_tag' taxonomy.
 354           *
 355           * @since 2.3.0
 356           *
 357           * @param WP_Term[]|int|WP_Error $tags Array of 'post_tag' term objects, a count thereof,
 358           *                                     or WP_Error if any of the taxonomies do not exist.
 359           * @param array                  $args An array of arguments. See {@see get_terms()}.
 360           */
 361          $tags = apply_filters( 'get_tags', $tags, $args );
 362      }
 363  
 364      return $tags;
 365  }
 366  
 367  /**
 368   * Retrieves a post tag by tag ID or tag object.
 369   *
 370   * If you pass the $tag parameter an object, which is assumed to be the tag row
 371   * object retrieved from the database, it will cache the tag data.
 372   *
 373   * If you pass $tag an integer of the tag ID, then that tag will be retrieved
 374   * from the database, if it isn't already cached, and passed back.
 375   *
 376   * If you look at get_term(), both types will be passed through several filters
 377   * and finally sanitized based on the $filter parameter value.
 378   *
 379   * @since 2.3.0
 380   *
 381   * @param int|WP_Term|object $tag    A tag ID or object.
 382   * @param string             $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 383   *                                   correspond to a WP_Term object, an associative array, or a numeric array,
 384   *                                   respectively. Default OBJECT.
 385   * @param string             $filter Optional. How to sanitize tag fields. Default 'raw'.
 386   * @return WP_Term|array|WP_Error|null Tag data in type defined by $output parameter.
 387   *                                     WP_Error if $tag is empty, null if it does not exist.
 388   *
 389   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
 390   * @phpstan-return (
 391   *     $output is 'ARRAY_A' ? array<string, mixed>|WP_Error|null : (
 392   *         $output is 'ARRAY_N' ? list<mixed>|WP_Error|null : WP_Term|WP_Error|null
 393   *     )
 394   * )
 395   */
 396  function get_tag( $tag, $output = OBJECT, $filter = 'raw' ) {
 397      return get_term( $tag, 'post_tag', $output, $filter );
 398  }
 399  
 400  /* Cache */
 401  
 402  /**
 403   * Removes the category cache data based on ID.
 404   *
 405   * @since 2.1.0
 406   *
 407   * @param int $id Category ID
 408   */
 409  function clean_category_cache( $id ) {
 410      clean_term_cache( $id, 'category' );
 411  }
 412  
 413  /**
 414   * Updates category structure to old pre-2.3 from new taxonomy structure.
 415   *
 416   * This function was added for the taxonomy support to update the new category
 417   * structure with the old category one. This will maintain compatibility with
 418   * plugins and themes which depend on the old key or property names.
 419   *
 420   * The parameter should only be passed a variable and not create the array or
 421   * object inline to the parameter. The reason for this is that parameter is
 422   * passed by reference and PHP will fail unless it has the variable.
 423   *
 424   * There is no return value, because everything is updated on the variable you
 425   * pass to it. This is one of the features with using pass by reference in PHP.
 426   *
 427   * @since 2.3.0
 428   * @since 4.4.0 The `$category` parameter now also accepts a WP_Term object.
 429   * @access private
 430   *
 431   * @param array|object|WP_Term $category Category row object or array.
 432   */
 433  function _make_cat_compat( &$category ) {
 434      if ( is_object( $category ) && ! is_wp_error( $category ) ) {
 435          $category->cat_ID               = $category->term_id;
 436          $category->category_count       = $category->count;
 437          $category->category_description = $category->description;
 438          $category->cat_name             = $category->name;
 439          $category->category_nicename    = $category->slug;
 440          $category->category_parent      = $category->parent;
 441      } elseif ( is_array( $category ) && isset( $category['term_id'] ) ) {
 442          $category['cat_ID']               = &$category['term_id'];
 443          $category['category_count']       = &$category['count'];
 444          $category['category_description'] = &$category['description'];
 445          $category['cat_name']             = &$category['name'];
 446          $category['category_nicename']    = &$category['slug'];
 447          $category['category_parent']      = &$category['parent'];
 448      }
 449  }


Generated : Fri Oct 2 08:20:29 2026 Cross-referenced by PHPXref