WORDPRESSIntermediate

How to Get WordPress Categories

PB Pb28 Master Team July 12th, 2022 Intermediate

๐Ÿ“ฆ Get the complete source code for this tutorial

In WordPress there are many in-built functions to get all categories. These are, wp_list_categories(), get_categories(), wp_dropdown_categories() and wp_terms_checklist(). These functions are varied based on the output format of the category result they return.

These WordPress functions accept a list of optional parameters to filter categories. These parameter lists can be an array or a query string. In this tutorial, we are going to see a short note about these functions and the usage procedure.

wp_list_catergories()

wp_list_categories() creates and returns a formatted HTML code to display category lists. This function allows us to work on the formatted results by using custom walker class. This class extends Walker_Category to parse the category results.

The way of using this function is,

php
<?php 

    $args = array(

	'style'      => 'list',

	'hide_empty' => 1,

	);

    wp_list_categories($args); 

?>

<?php 

	wp_list_categories(style=list&hide_empty=1); 

?>

get_categories()

This WordPress function returns categories in an object array. From this array, we can retrieve categories to create our own format. And the code is,

php
<?php 

    $args = array(

	'style'      => 'list',

	'hide_empty' => 1,

	);

    get_categories($args); 

?>

<?php 

	get_categories(style=list&hide_empty=1); 

?>

This function returns WordPress categories as a dropdown list. And the way to use this function is,

php
<?php 

    $args = array(

	'style'       => 'list',

	'hide_empty'  => 1,

	);

    wp_dropdown_categories( $args ); 

?>

wp_terms_checklist()

Similarly, this function returns category checkbox. wp_terms_checklist() function accepts 6 optional parameters. The code is,

php
<?php 

    wp_terms_checklist($postid,$decendent_and_self,$selected_categories,$popular_categories,$walker,$checked_ontop); 

?>

and the parameters are,

  • $postid โ€“ To check specified post categories.
  • $decendent_and_self โ€“ To return specified category checkbox with its dependent Category checkboxes.
  • $selected_categories โ€“ To check specified array of categories.
  • $popular_categories โ€“ To override popular categories.
  • $walker โ€“ To work with the resultant HTML.
  • $checked_ontop โ€“ To move checked boxes to the top of the category tree.

๐Ÿ“ฆ Download the full project files and try it locally