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


Generated : Thu Apr 18 08:20:02 2024 Cross-referenced by PHPXref