get_terms()

最后更新于:2021-11-27 00:54:56

get_terms( array|string$args=array(), array|string$deprecated=”)

Retrieves the terms in a given taxonomy or list of taxonomies.

参数

$args

(array|string) (Optional) Array or string of arguments. See GC_Term_Query::__construct() for information on accepted arguments.

Default value: array()

$deprecated

(array|string) (Optional) Argument array, when using the legacy function parameter format. If present, this parameter will be interpreted as $args, and the first function parameter will be parsed as a taxonomy or array of taxonomies.

Default value: ”

响应

(GC_Term[]|int[]|string[]|string|GC_Error) Array of terms, a count thereof as a numeric string, or GC_Error if any of the taxonomies do not exist. See the function description for more information.

源文件

文件: gc-includes/taxonomy.php

function get_terms( $args = array(), $deprecated = '' ) {
	$term_query = new GC_Term_Query();

	$defaults = array(
		'suppress_filter' => false,
	);

	/*
	 * Legacy argument format ($taxonomy, $args) takes precedence.
	 *
	 * We detect legacy argument format by checking if
	 * (a) a second non-empty parameter is passed, or
	 * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
	 */
	$_args          = gc_parse_args( $args );
	$key_intersect  = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
	$do_legacy_args = $deprecated || empty( $key_intersect );

	if ( $do_legacy_args ) {
		$taxonomies       = (array) $args;
		$args             = gc_parse_args( $deprecated, $defaults );
		$args['taxonomy'] = $taxonomies;
	} else {
		$args = gc_parse_args( $args, $defaults );
		if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
			$args['taxonomy'] = (array) $args['taxonomy'];
		}
	}

	if ( ! empty( $args['taxonomy'] ) ) {
		foreach ( $args['taxonomy'] as $taxonomy ) {
			if ( ! taxonomy_exists( $taxonomy ) ) {
				return new GC_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
			}
		}
	}

	// Don't pass suppress_filter to GC_Term_Query.
	$suppress_filter = $args['suppress_filter'];
	unset( $args['suppress_filter'] );

	$terms = $term_query->query( $args );

	// Count queries are not filtered, for legacy reasons.
	if ( ! is_array( $terms ) ) {
		return $terms;
	}

	if ( $suppress_filter ) {
		return $terms;
	}

	/**
	 * Filters the found terms.
	 *
	 * @since 2.3.0
	 * @since 4.6.0 Added the `$term_query` parameter.
	 *
	 * @param array         $terms      Array of found terms.
	 * @param array         $taxonomies An array of taxonomies.
	 * @param array         $args       An array of get_terms() arguments.
	 * @param GC_Term_Query $term_query The GC_Term_Query object.
	 */
	return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
}
$get_terms_default_attributes = array (
			'taxonomy' => 'category', //empty string(''), false, 0 don't work, and return empty array
			'orderby' => 'name',
			'order' => 'ASC',
			'hide_empty' => true, //can be 1, '1' too
			'include' => 'all', //empty string(''), false, 0 don't work, and return empty array
			'exclude' => 'all', //empty string(''), false, 0 don't work, and return empty array
			'exclude_tree' => 'all', //empty string(''), false, 0 don't work, and return empty array
			'number' => false, //can be 0, '0', '' too
			'offset' => '',
			'fields' => 'all',
			'name' => '',
			'slug' => '',
			'hierarchical' => true, //can be 1, '1' too
			'search' => '',
			'name__like' => '',
			'description__like' => '',
			'pad_counts' => false, //can be 0, '0', '' too
			'get' => '',
			'child_of' => false, //can be 0, '0', '' too
			'childless' => false,
			'cache_domain' => 'core',
			'update_term_meta_cache' => true, //can be 1, '1' too
			'meta_query' => '',
			'meta_key' => array(),
			'meta_value'=> '',
	);
array(1) {
  [0]=>
  object(GC_Term) (11) {
    ["term_id"]=>  //int
    ["name"]=>	//string 
    ["slug"]=>  //string 
    ["term_group"]=>  //int
    ["term_taxonomy_id"]=> //int
    ["taxonomy"]=>	//string
    ["description"]=>	//string
    ["parent"]=>	//int
    ["count"]=>	// int
    ["filter"]=>	//string
    ["meta"]=> array(0) { // presumably this would be some returned meta-data?
    }
  }
}
$taxonomies = get_terms( array(
	'taxonomy' => 'taxonomy_name',
	'hide_empty' => false
) );

if ( !empty($taxonomies) ) :
	$output = '<select>';
	foreach( $taxonomies as $category ) {
		if( $category->parent == 0 ) {
			$output.= '<optgroup label="'. esc_attr( $category->name ) .'">';
			foreach( $taxonomies as $subcategory ) {
				if($subcategory->parent == $category->term_id) {
				$output.= '<option value="'. esc_attr( $subcategory->term_id ) .'">
					'. esc_html( $subcategory->name ) .'</option>';
				}
			}
			$output.='</optgroup>';
		}
	}
	$output.='</select>';
	echo $output;
endif;
// Define Featured Category IDs first
$featured_category_ids = array();
// It must be output GC_Object
$featured_categories = get_field('main_category_filters');

// Creating loop to insert IDs to array.
foreach( $featured_categories as $cat ) {
	$featured_category_ids[] = $cat->term_id;
}

// Now, if Featured Categories are match, add their IDs via 'exclude'
if( $featured_categories ) {
	$args = array(
		'taxonomy' => 'event_cat',
		'parent' => 0,
		'exclude' => $featured_category_ids
	);
} else {
    // If no featured, just display all terms
	$args = array(
		'taxonomy' => 'event_cat',
		'parent' => 0
	);
}

// Starting query terms now
$other_categories = get_terms($args);
$args = array( 'hide_empty=0' );

$terms = get_terms( 'my_term', $args );
if ( ! empty( $terms ) && ! is_gc_error( $terms ) ) {
	$count = count( $terms );
	$i = 0;
	$term_list = '<p class="my_term-archive">';
	foreach ( $terms as $term ) {
		$i++;
		$term_list .= '<a href="' . esc_url( get_term_link( $term ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $term->name ) ) . '">' . $term->name . '</a>';
		if ( $count != $i ) {
			$term_list .= ' &middot; ';
		}
		else {
			$term_list .= '</p>';
		}
	}
	echo $term_list;
}
$term_query = new GC_Term_Query( array( 
    'taxonomy' => 'regions', // <-- Custom Taxonomy name..
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'child_of'               => 0,
    'parent'                 => 0,
    'fields'                 => 'all',
    'hide_empty'             => false,
) );

// Show Array info
echo '<pre>';
print_r( $term_query->terms );
echo '</pre>';


//Render html
if ( ! empty( $term_query->terms ) ) {
    foreach ( $term_query->terms as $term ) {
        echo gc_kses_post( $term->name ) . ", ";
        echo esc_html( $term->term_id ) . ", ";
        echo esc_html( $term->slug ) . ", ";
        echo "<br>";
    }
} else {
    echo 'No term found.';
}
$terms = get_terms( array(
    'taxonomy' => 'tax_slug',
    'hide_empty' => false,
    'meta_query' => array(
        [
            'key' => 'meta_key_slug_1',
            'value' => 'desired value to look for'
        ]
    ),
    'meta_key' => 'meta_key_slug_2',
    'orderby' => 'meta_key_slug_2'

) );
$taxonomies = get_terms( array(
    'taxonomy' => 'product_cat', //Custom taxonomy name
    'hide_empty' => false
) );
if ( !empty($taxonomies) ) :
    foreach( $taxonomies as $category ) {
        if( $category->parent == 0 ) {
            
            //remove uncategorized from loop
            if( $category->slug == 'uncategorized' ){
                continue;
            }

            //Parent category information
 			echo esc_html__($category->name, 'text-domain');
 			echo esc_html__($category->description, 'text-domain');
 			echo esc_html__($category->slug, 'text-domain');
 			echo esc_html__($category->count, 'text-domain');


 			//Sub category information
	        foreach( $taxonomies as $subcategory ) {
	            if($subcategory->parent == $category->term_id) {
			        echo esc_html__($subcategory->name, 'text-domain');
			        echo esc_html__($subcategory->description, 'text-domain');
			        echo esc_html__($subcategory->slug, 'text-domain');
			        echo esc_html__($subcategory->count, 'text-domain');
	            }
	        }

        }
    }
endif;
function get_child_taxonomies( $taxonomy_name, $termId, $args = array() ) {
	$defaults = array(
		'taxonomy'   => $taxonomy_name,
		'orderby'    => 'name',
		'order'      => 'ASC',
		'hide_empty' => true,
		'child_of'   => $termId,
	);

	$args       = gc_parse_args( $args, $defaults );
	$taxonomies = get_terms( $args );

	if ( empty( $taxonomies ) || is_gc_error( $taxonomies ) ) {
		return false;
	}	
	return $taxonomies;

}
function custom_get_term_lit( $taxonomy = 'category' ) {
    $terms = get_terms( [
        'taxonomy'   => $taxonomy,
        'hide_empty' => false,
    ] );
    if ( ! empty( $terms ) && ! is_gc_error( $terms ) ) {
        return gc_list_pluck( $terms, 'name', 'term_id' );
    }
    return false;
}

$category = custom_get_term_lit('custom-taxonomy-id');
echo "<select name='category' id='category-dropdown'>";
foreach ( $category as $cat_id => $cat_name ) {
    echo "<option value='" . esc_attr( $cat_id ) . "'>" . esc_html__( $cat_name, 'text-domain' ) . "</option>";
}
echo "</select>";
    $taxonomy = 'my_taxonomy';

    function listTaxonomies($taxonomy,$term_id = '0') {
        $output = '';

        $args = array(
            'taxonomy' => $taxonomy,
            'parent' => $term_id
        );
        $categories = get_terms($args);

        if($categories) {
			$output.= '<div style="padding-left:2em;">';
            foreach( $categories as $category ) {
                $output.= esc_attr( $category->name ) . ' (' . $category->slug . ')<br>';
                $output.= listTaxonomies($taxonomy,$category->term_id);
            }
			$output.= '</div>';
        }
        return $output;
    }

    listTaxonomies($taxonomy);
function taxonomy_list_dropdown($type, $post_type) {
  $terms = get_terms($type);
  $category = taxonomy_current($type);

  if ( !empty( $terms ) &amp;&amp; !is_gc_error( $terms ) ){
    the_terms_list(
      'categories__dropdown icon-dropdown',
      array(
        'show_option_all'  => 'Click to filter',
        'taxonomy'         => $type,
        'current_category' => $category->term_id,
        'value_field'      => 'slug',
        'selected'         => $category->slug,
      ),
      'dropdown',
      'data-module-init="redirect-dropdown"'
    );
  }
}