WordPress get category by slug

Developer Resources

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

Contents

Description

You can fully inject any customizations to the query before it is sent, as well as control the output with a filter.

The return type varies depending on the value passed to $args[‘fields’] . See WP_Term_Query::get_terms() for details. In all cases, a WP_Error object will be returned if an invalid taxonomy is requested.

The ‘get_terms’ filter will be called when the cache has the term and will pass the found term along with the array of $taxonomies and array of $args.
This filter is also called before the array of terms is passed and will pass the array of terms, along with the $taxonomies and $args.

The ‘list_terms_exclusions’ filter passes the compiled exclusions along with the $args.

The ‘get_terms_orderby’ filter passes the ORDER BY clause for the query along with the $args array.

Prior to 4.5.0, the first parameter of get_terms() was a taxonomy or list of taxonomies:

Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array:

Parameters

$deprecated array | string Optional

Return

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

Source

Hooks

Filters the found terms.

Uses

Determines whether the taxonomy name exists.

Retrieves the translation of $text.

Merges user defined arguments into defaults array.

Calls the callback functions that have been added to a filter hook.

Initializes the error.

Used By

Uses Description
WP_Term_Query::__construct() wp-includes/class-wp-term-query.php
Used By

Displays a formats drop-down for filtering items.

Sanitizes POST values from an input taxonomy metabox.

Retrieves terms associated with a taxonomy.

Retrieves the query results.

Performs post queries for available-item searching.

Performs the post_type and taxonomy queries for loading available menu items.

Generates the WXR export file for download.

Outputs an unordered list of checkbox input elements labelled with term names.

Retrieves a list of the most popular terms from the specified taxonomy.

Outputs a link category checklist element.

Ajax handler for getting a tagcloud.

Ajax handler for tag search.

Prints the appropriate response to a menu quick search.

Displays a meta box for a taxonomy menu item.

Starts the element output.

Displays a tag cloud.

Displays or retrieves the HTML dropdown list of categories.

Retrieves all post tags.

Retrieves a list of category objects.

Retrieves a category based on URL containing the category slug.

Retrieves all category IDs.

Outputs the settings form for the Links widget.

Retrieves children of taxonomy as term IDs.

Retrieves the terms associated with the given object(s), in the supplied taxonomies.

Adds a new term to the database.

Counts how many terms are in taxonomy.

Gets all term data from database by term field and data.

Determines whether a taxonomy term exists.

Retrieves or echoes all of the bookmarks.

Returns all navigation menu objects.

Retrieve all terms for a taxonomy.

Helper method for wp_newPost() and wp_editPost(), containing shared logic.

Changelog

Used By Description
WP_Posts_List_Table::formats_dropdown() wp-admin/includes/class-wp-posts-list-table.php
WP_REST_Terms_Controller::get_items() wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php
WP_Customize_Nav_Menus::search_available_items_query() wp-includes/class-wp-customize-nav-menus.php
WP_Customize_Nav_Menus::load_available_items_query() wp-includes/class-wp-customize-nav-menus.php
WP_Terms_List_Table::prepare_items() wp-admin/includes/class-wp-terms-list-table.php
_wp_ajax_menu_quick_search() wp-admin/includes/nav-menu.php
Walker_Category::start_el() wp-includes/class-walker-category.php
WP_Widget_Links::form() wp-includes/widgets/class-wp-widget-links.php
wp_xmlrpc_server::wp_getTerms() wp-includes/class-wp-xmlrpc-server.php
wp_xmlrpc_server::_insert_post() wp-includes/class-wp-xmlrpc-server.php
Changelog
Version Description
4.8.0 Introduced ‘suppress_filter’ parameter.
4.5.0 Changed the function signature so that the $args array can be provided as the first parameter.
Introduced ‘meta_key’ and ‘meta_value’ parameters. Introduced the ability to order results by metadata.
4.4.0 Introduced the ability to pass ‘term_id’ as an alias of ‘id’ for the orderby parameter.
Introduced the ‘meta_query’ and ‘update_term_meta_cache’ parameters. Converted to return a list of WP_Term objects.
4.2.0 Introduced ‘name’ and ‘childless’ parameters.
2.3.0 Introduced.

User Contributed Notes

All get_terms attributes with default values:
(I try default from this article and it didn’t work. This works.)

As of WordPress 4.6.1, here’s the array that’s returned (to add to Leo’s helpful note above)

If parent => 0 is passed, only top-level terms will be returned

Get categories and subcategories by custom taxonomies:

Working with Advanced Custom Fields (field type: Taxonomy, output: Object) for filtering taxonomies.

Case: Create a filter with main categories defined by ACF field, and all another should belongs to *others*.

Solution:

Get all post categories ordered by count.

Get all the links categories:

List all the terms in a custom taxonomy, without a link:

List all the terms, with link to term archive, separated by an interpunct (·):

Get all post categories ordered by count.

List terms limit to those matching a specific metadata key and metadata value

Get list of terms that match a certain meta_key

If `get_terms` doesnt works for some odd reason with custom taxonomy not showing registered, try using `WP_Term_Query`:

‘; //Render html if ( ! empty( $term_query->terms ) ) < foreach ( $term_query->terms as $term ) < echo wp_kses_post( $term->name ) . «, «; echo esc_html( $term->term_id ) . «, «; echo esc_html( $term->slug ) . «, «; echo «
«; > > else

Custom Taxonomy and Sub Category Lists.
Your can use this to create list table also.

Meta Query using a custom field, and then ordering using a different custom field.

Order by parent term ID – not documented, but also works.

Get all child taxonomy of a parent taxonomy

Get All Terms id and name in a array for make dropdown select:

list categories( or custom taxonomy ) and subcategory in organazid way

If you have a term assigned to something else than a post, here is a warning:
‘hide_empty’ is default true so it only shows terms assigned to posts. So if you get an empty Array returned be aware that terms (e.g. categories) assigned to attachments for example are not shown by default unless you use ‘hide_empty’ => false :

Be very careful as the code below:

can return valid terms, but can also return a WP_Error if, for example, the taxonomy is invalid…

Therefore this check alone isn’t enough to save you from bugs in your code:

Instead, better to use the one below:

Categories and Tags are the two pre-defined Taxonomies. The Taxonomy Name, when included as an element ‘taxonomy’ of the array specified as the first parameter $args, has a value of ‘category’ for Categories and ‘post_tag’ for Tags.
‘taxonomy’ => ‘category’
‘taxonomy’ => ‘post_tag’

Loop through taxonomy and list all subcategories.

Get Terms filtered by first letter

Get terms ordered by value of meta-key:

You must log in before being able to contribute a note or feedback.

Источник

Developer Resources

Retrieves a list of category objects.

Contents

Description

If you set the ‘taxonomy’ argument to ‘link_category’, the link categories will be returned instead.

See also

  • get_terms(): Type of arguments that can be changed.

Parameters

Return

array List of category objects.

Source

Hooks

Filters the taxonomy used to retrieve terms when calling get_categories() .

Uses

Updates category structure to old pre-2.3 from new taxonomy structure.

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

Retrieves the translation of $text.

Marks a function argument as deprecated and inform when it has been used.

Merges user defined arguments into defaults array.

Calls the callback functions that have been added to a filter hook.

Checks whether the given variable is a WordPress Error.

Used By

Uses Description
_make_cat_compat() wp-includes/category.php
Used By

Generates the WXR export file for download.

Legacy function used for generating a categories drop-down control.

Displays or retrieves the HTML list of categories.

Output entire list of links by category.

Retrieve the list of categories on a given blog.

Retrieve list of all categories on blog.

Retrieve category list.

Changelog

Used By Description
export_wp() wp-admin/includes/export.php
wp_xmlrpc_server::mw_getCategories() wp-includes/class-wp-xmlrpc-server.php
wp_xmlrpc_server::mt_getCategoryList() wp-includes/class-wp-xmlrpc-server.php
wp_xmlrpc_server::wp_suggestCategories() wp-includes/class-wp-xmlrpc-server.php
Changelog
Version Description
2.1.0 Introduced.

User Contributed Notes

List Categories and Descriptions
This example will list, in alphabetic order, all categories presented as links to the corresponding category archive. Each category description is listed after the category link.

Function only returns categories in use by posts

It is very important to note that by default, the get_category() will ONLY return categories that ARE IN USE. This means if no post is assigned to the category, then the category object for that category is not returned.

This means if you are developer, and you created a category (maybe during testing), you should supply an argument array having the ‘hide_empty’ => false in it. Check the example usage below.

Get only top level categories
To get the top level categories only, set parent value to zero. This example gets link and name of top level categories.

Specific category parent title with linked menu of subcategories

– could be used in a sidebar application

If there are no categories to display, get_categories() will return an empty array.

Drop-down box as used in Parent category at post category page
This is the code used in the built-in category page.

The slightly altered code below will grab all categories and display them with indent for a new level (child category). The select box will have name and id attribute values of ‘select_name’. This select element will not display a default “none” as the original code was used to attach a category as a child to another category (or none).

Drop-down Box
Here’s how to create a drop-down box of the subcategories of, say, a category that archives information on past events.
This mirrors the example of the drop-down example of wp_get_archives() which shows how to create a drop-down box for monthly archives.

Suppose the category whose subcategories you want to show is category 10, and that its category “nicename” is “archives”.

You must log in before being able to contribute a note or feedback.

Источник

How To Get Categories and Subcategories in WordPress

Updated on December 8, 2021

The the_category() template function is often used in WordPress theme development. It displays the parent category and any child categories. In several instances, this function could generate a long list. The problem becomes important when a website has a large number of categories and subcategories. In such WordPress get category cases, the_catagory() function often create a huge list that is often less than useful for the task.

Get Specific Post Category

The following code will get the category of a specific post. Please note that you have to add this code to either content-single.php or single.php

Get Subcategory from Parent Category

First, get the subcategory from the parent category for a particular post. Next, add the following code in the post template where the index and archive post loop start. You could also add this code after the title.

Name of Category Get by ID

Description of Category (Through ID)

Category slug is the URL name of that category:

Description of Category (Get by Slug)

Category slug is the URL name of that category:

You can generate a link to a particular category using the id. Use the following code:

Wrapping up!

In this article, I discussed how to get specific post category, subcategory from parent category, category name by ID, category description by ID and category link by ID.

If you need help with the code or would like to add to the discussion, do leave a comment below.

Share This Article

Customer Review at

“Beautifully optimized hosting for WordPress and Magento”

Arda Burak [Agency Owner]

Owais Alam

is the WordPress Community Manager at Cloudways — A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]

Источник

Читайте также:  Trove что за ошибка 2025
Поделиться с друзьями
КомпСовет
Adblock
detector