If you are looking for the best way to link to WooCommerce category, this post will guide you and help create WooCommerce link to category.
When you are creating WooCommerce plugin or theme you may possibly want to create WooCommerce link to category page. If this is what you are looking for, this post will guide you step by step.
WooCommerce Link to Category
The first step is to understand how you can get the specific category that you want to link to.
Step 1: Get WooCommerce Category ID
You can use the get_cat_ID() function to get the category ID that you will later use to get the category URL so that you can create the WooCommerce link to category.
The following is the code you can use to get the WooCommerce category ID
$cat_id = get_cat_ID(“Category Name”);
This function retrieves the ID of a category from its name. The parameter is a string and the basic expression of the function is as follows:
get_cat_ID( string $cat_name );
Step 2 : Get the WooCommerce Category URL
To link to WooCommerce category we need to get the link of the category. In this case we will use another function that is used to get the link from an ID in WordPress.
$cat_url = get_category_link($cat_id);
This function is used to retrieve the category link URL and it takes one parameter which is an integer or an object.
In this case, we are passing the category ID that we obtained in the first step which is an integer.
The general expression of this function is as follows :
get_category_link( int|object $category )
Step 3: Use | Display the Category in a Link
You can now use the results of the second step to add the WooComerce category link in a HTML link as shown in the code below:
<a href=”<?php echo <a href="https://codex.wordpress.org/Function_Reference/esc_url">esc_url</a>( $cat_url); ?>” title=”Display Category”>Display Category</a>
In this post we have highlighted how you can create WooCommerce link to category by obtaining the category ID and URL using the default WordPress functions.
If you know the category name you can easily obtain the category ID and the category link and use them to create WooCommerce link to category.
If you don’t have the WooCommerce category name, you can use the get_the_category() function that returns the category object that you can obtain all the other details you need to use to get the category link.