wordpress category development

WordPress Category PHP Development

WordPress category is one of the default taxonomies. WordPress uses taxonomies (a group of items like the category) to list and group content. WordPress categories are a very convenient way to organize your posts. Even you can create a custom template for the category list in WordPress. In this article, we are going to discuss how to create and delete a WordPress category in Dashboard and PHP code, how to get details of the category like id, name, description, slug, link, and even the subcategory, and how to display the category in a template, list, loop, archive page, and menu.

Categories provide a helpful way to group related blog posts together. You might want to create categories for different topics you cover in your blog. You can use categories to sort and group your blog posts into different sections. For example, if you have articles that cover a specific genre of music, you might want to keep those grouped together in a category.

Categories not only help keep posts organized, but you can also use categories to display posts in several places across your site and help visitors quickly know what topics your website is about and allows them to navigate your site faster. Similar to the use of tags in WordPress, people search through categories to find similar topics and subjects.

You can have parent and child categories, making hierarchical arrangements of your posts possible. In addition, one post can be placed in more than one category. This gives you a lot of flexibility to show exactly the posts you want, exactly the way you want them in widgets, menus, or directly in your WordPress theme.

How to create a WordPress category?

To create a new category in WordPress, go to Posts > Categories page. On the left side of the page, you will see a tab that allows you to create categories. Fill in the category name, its slug (which will be used in the category URLs), and the category description, and then press Add New Category.

In this menu, you can delete and update categories too. Not only on this page even on the posting page when you are writing a post, you can also create a category. To do this in the Post section you can see the Categories section in the post settings.

How to use WordPress categories

WordPress categories are a great way to organize your WordPress blog. You should create a few categories based on what you think you’ll be writing about on your website.

For example, you are writing a post about family. You could create a category named “Family”. If you find your categories overfilled with articles, you can create child categories (subcategories), a category within a category. This is telling you that you can create subcategories like “Nephews“.

Setting up categories in WordPress in this way will help your readers and Google make sense of the organizational structure of your website. In addition, categories are a great way for people to find similar topics they are interested in without looking through your website for ages.

Once you have the category structure created, you can add posts to categories. Open a particular post (or write a new one) and place a checkbox in the category you want to assign it to.

How to add a category to the menu in WordPress

Adding a category to your WordPress menu bar allows readers to easily find your content and navigate to a related group of blog posts.

Go back to your Dashboard > Appearance > Menus. Expand the categories panel on the left-hand side and you’ll see all of the categories.

Select the categories that you’d like to display on the menu and click the ADD TO MENU button.

If there is no categories panel, expand the screen options on the top and check the “Categories”. Now you can find the categories panel to add the category in the menu in WordPress.

Display categories in the post

Displaying categories can be done in some ways. One of them is in the post. When you are going to read a WordPress post, you could see that this post belongs to some categories (one or more). To display these categories in your post loop in WordPress you could use the below code.

while ( have_posts() ) :
	the_post();
        .
        .
        $categories = get_the_category();
	foreach($categories as $category){
		echo $category->name . wp_get_list_item_separator();
	}
        .
        .
endwhile;

Output

Category 1,Category 2,Category 3,

The get_the_category() built-in WordPress function returns WP_Term which is the list of details like term_id, name, slug, description, and so on of the category.

  • term_id
  • name
  • slug
  • term_group
  • term_taxonomy_id
  • taxonomy
  • category
  • description
  • parent
  • count
  • filter
  • cat_ID
  • category_count
  • category_description
  • cat_name
  • category_nicename
  • category_parent

If you wanna use this function outside the loop, you have to pass the post id as a parameter.

get_the_category($post_id );

In this example, you have to control the separator yourself. The other thing is that the category names are not linked and clickable it is better to use the get_the_category_list() function instead.

There is another neat and convenient way to display post categories inside the loop in WordPress. The get_the_category_list() function displays the categories with extra options.

while ( have_posts() ) :
	the_post();
        .
        .
        $categories_list = get_the_category_list( wp_get_list_item_separator() );
	if ( $categories_list ) {
		printf(
			/* translators: %s: List of categories. */
			'<span class="cat-links">' . esc_html__( 'Categorized as %s', 'textdomain' ) . ' </span>',
			$categories_list // phpcs:ignore WordPress.Security.EscapeOutput
		);
	}
        .
        .
endwhile;

Output

Categorized as Category 1,Category 2,Category 3

In this example, you could display WordPress category list names, and the names are linked to the category list display section. Also, you can use this method to display WordPress custom post type categories.

Read more about WordPress Custom Post Type

How to Create Category Template archive page in WordPress

With WordPress websites, it’s common to use a different template archive page for a category, tag, custom post type, and taxonomy. By creating templates for categories, you can add specific features to category archive pages.

For example, you can allow users to subscribe to categories, add category images, show category descriptions and choose a different layout for each category.

To create and design a WordPress category archive template, you need to create a page template for that particular category. Go to your theme’s folder. From the list of theme files, open the category.php file, if you do not have a category.php file there, then create one.

In the case of categories, the hierarchy is fairly simple. For instance, suppose the slug of the category is the news and the Category ID is 6. The Template Hierarchy specifies that WordPress will use the first template file it finds in your current theme’s directory from the following list:

  1. category-slug.php
  2. category-ID.php
  3. category.php
  4. archive.php
  5. index.php

That is, if you do not have a category-slug.php (let’s say category-news.php), WordPress will check for a category-ID.php (like category-6.php), and so on.

Now open the category-news.php file and add the following codes to it.

<?php
get_header();
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
?>
<div class="wrapper">
  <div class="primary-content">
    <h1 class="archive-title"><?php echo apply_filters( 'the_title', $term->name ); ?> News</h1>

    <?php if ( !empty( $term->description ) ): ?>
    <div class="archive-description">
      <?php echo esc_html($term->description); ?>
    </div>
    <?php endif; ?>

    <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>

    <div id="post-<?php the_ID(); ?>" <?php post_class('post'); ?>>
      <h2 class="post-title"><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
        <div class="post-info">
          <p><?php the_time(get_option('date_format')); ?> by <?php the_author_posts_link(); ?></p>
        </div>
        <div class="entry">
          <?php the_content( __('Full story…') ); ?>
        </div>
    </div>

    <?php endwhile; ?>

    <?php else: ?>

    <h2 class="post-title">No Post Type in <?php echo apply_filters( 'the_title', $term->name ); ?></h2>
    <div class="content clearfix">
      <div class="entry">
        <p>It seems there isn't anything happening in <strong><?php echo apply_filters( 'the_title', $term->name ); ?></strong> right now. Check back later, something is bound to happen soon.</p>
      </div>
    </div>

    <?php endif; ?>
  </div>

<?php get_footer(); ?>

This is an example of the WordPress category template for displaying the list and archive of category posts.

How to display all categories in WordPress?

If you want to display all category details list of WordPress, you could use the get_categories() function. For example, you have a widget and you want to user select a category from the list. This function retrieves all post categories from WordPress.

$categories = get_categories();
foreach($categories as $category){
	echo esc_html($category->name) . wp_get_list_item_separator();
}

To display all categories with subcategories, you could use this function with a little trick.

$args = array(
	'hide_empty' => false,
	'parent' => 0,
);
$categories = get_categories($args);
foreach($categories as $category){
	echo $category->name . '<br/>';
	$args = array(
		'parent' => $category->term_id,
		'hide_empty' => false,
        );
	$sub_categories = get_categories( $args );
	foreach($sub_categories as $sub_category) { 
		echo '- ' . $sub_category->name  . '<br/>'; 
	}
}

There is a little problem with this code. If you have multi-level subcategories you have to use recursive functions to display the subcategories.

How to display all categories of the custom post type in WordPress?

Custom post types are like posts and pages. Let’s assume that you have created a custom post type and created a custom taxonomy as a category (named “hscategory”). With this code, you can retrieve all categories of the custom post type.

$args = array(
	'taxonomy' => 'hscategory',
	'hide_empty' => false,
	'orderby' => 'name',
	'order'   => 'ASC'
);
$categories = get_categories($args);
foreach($categories as $category){
	echo esc_html($category->name) . wp_get_list_item_separator();
}

The “hscategory” is the custom taxonomy slug of your custom post type.

If you want to display a subcategory, you could use the following code.

$args = array(
	'taxonomy' => 'hscategory',
	'hide_empty' => false,
	'parent' => 0,
);
$categories = get_categories($args);
foreach($categories as $category){
	echo $category->name . '<br/>';
	$args = array(
		'taxonomy' => 'hscategory',
		'parent' => $category->term_id,
		'hide_empty' => false,
	);
	$sub_categories = get_categories( $args );
	foreach($sub_categories as $sub_category) { 
		echo '- ' . $sub_category->name  . '<br/>'; 
	}
}

That little problem is still here. If you have multi-level subcategories you have to use recursive functions to display the subcategories.

How to create a WordPress category programmatically

If you want to create a category in WordPress by code, simply you can use the wp_insert_term() function like below.

wp_insert_term(
	// the name of the category
	'Category A', 		
	// the taxonomy, which in this case if category (don't change)
	'category', 		
	array(			
		'slug' => 'category-a',  
	)
);

If you want to create a category for your custom post type in WordPress, just change the “category” to your post type category slug. Which in this case is “hscategory”.

wp_insert_term(
	// the name of the category
	'Category A', 		
	// the taxonomy, which in this case if category (don't change)
	'hscategory', 		
	array(			
		'slug' => 'category-a',  
	)
);

To create a subcategory for the parent category you change the code a little bit.

wp_insert_term(
	// the name of the sub-category
	'Sub-category 1', 				
	// the taxonomy 'category' (don't change)
	'category',
	array(
		'slug' => 'sub-cat-1', 
		// link with main category. In the case, become a child of the "Category A" parent  
		'parent'=> term_exists( 'Category A', 'category' )['term_id']
	)
);

And for the custom post type category

wp_insert_term(
	// the name of the sub-category
	'Sub-category 1', 				
	// the taxonomy 'category' (don't change)
	'hscategory',
	array(
		'slug' => 'sub-cat-1', 
		// link with main category. In the case, become a child of the "Category A" parent  
		'parent'=> term_exists( 'Category A', 'hscategory' )['term_id']
	)
);

How to delete a category programmatically in WordPress

To delete a category by code, use the below code.

$categ_ID = 204;
if ( wp_delete_category( $categ_ID ) ) {
	echo "Category #$categ_ID was successfully deleted";
} else {
	echo "Category #$categ_ID deletion failed";
}

The wp_delete_category() WordPress built-in function is used to delete a category.

How to get category link by ID

In this example, you have your category ID and you want to get the category link by its ID.

get_category_link( $category_id );

How to get category slug by ID in WordPress

You can get the WordPress category slug and other details by ID with the get_category() function.

$cat = get_category($category_id);
echo $cat->slug;

This function returns WP_Term which is the list of details like term_id, name, slug, and so on that, we discussed above.

Check if the page is a category page by the is_category() function

is_category();
// When any Category archive page is being displayed.

is_category( '204' );
// When the archive page for Category 204 is being displayed.

is_category( 'Category One' );
// When the archive page for the Category with Name "Category One" is being displayed.

is_category( 'category-slug' );
// When the archive page for the Category with Category Slug "category-slug" is being displayed.

is_category( array( 204, 'category-slug', 'Category One' ) );
// Returns true when the category of posts being displayed is either term_ID 204,
// or slug "category-slug", or name "Category One".
// Note: the array ability was added in version 2.5.

Get category description by ID in WordPress

If you want to display the WordPress category description by ID use the category_description() function.

echo category_description( $category_id );

You can write a description of your category in the categories menu that this description is one of the sections that are important for WordPress SEO. Some plugins like Yoast expands this description for users so that they can write a good description for the category in WordPress.

You may like

Shopping Cart