Search

How to Add Taxonomy Term in Custom Post Permalink in WordPress

Listen to this article
custom-permalink-wordpress
Taxonomy Term in Custom Post Permalink

Permalinks play an important role in the way a user perceives your website. A user friendly permalink is always easy on the eye for the user. It also tells the user what to expect exactly when the link shows up in the result for a search engine query. Hence, if the link is going to be one of the deciding factors in whether the user will be visiting your website or not then ‘Pretty Permalinks’ is the way to go.

One way to customize the permalink is to insert the taxonomy term in the post permalink, by setting the permalink to ‘%category%/%post_name%’. However this will not work with custom post type. It will work only for default posts.

Let us take an example. Suppose you want a ‘Projects’ section on your site. To make this section available on your website you have created ‘projects’ as a custom post type. Now you need to categorize your projects into a few categories like ‘WordPress’, ‘Drupal’, ‘Joomla’. Hence you have also created a taxonomy ‘project_categories’ for those categories. Technically, we call ‘WordPress’, ‘Drupal’, and ‘Joomla’ as terms of custom taxonomy ‘project_categories’.

So now if a user is viewing a project in the Projects section of your website, more specifically in the WordPress section then the URL should look like this.

[pre]http://abc.com/projects/wordpress/your-project-name[/pre]

 

Not a developer? Let our WordPress experts do the gruntwork for you!

Contact Us

 

Create a Custom Post Type and a Custom Taxonomy

You got the concept.. Right? So lets implement it now.
First we will create a custom post type and custom taxonomy. This can be done either using a plugin or with the help of code. If you’re opting for plugin and don’t know how to do it the read  ‘Creating Custom Post Type Using Plugin‘. However, if you want to implement this using code then open up the functions.php file and add below code to it.

<?php
add_action('init', 'projects_cpt');
function projects_cpt() {
    $labels = array(
        'name' => 'Projects',
        'singular_name' => 'Project',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Project',
        'edit_item' => 'Edit Project',
        'new_item' => 'New Project',
        'all_items' => 'All Projects',
        'view_item' => 'View Project',
        'search_items' => 'Search Projects',
        'not_found' => 'No projects found',
        'not_found_in_trash' => 'No projects found in Trash',
        'parent_item_colon' => '',
        'menu_name' => 'Projects'
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'query_var' => true,
        'taxonomies' => array('projectstype'),
        'rewrite' => array('slug' => 'projects/%projectscategory%', 'with_front' => false), 
        //Adding custom rewrite tag
        'capability_type' => 'post',
        'has_archive' => 'projectsarchives',
        'hierarchical' => false,
        'menu_position' => null,
        'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt'),
    );
    register_post_type('projects', $args);

    $labels = array(
        'name' => 'Projects Categories',
        'singular_name' => 'Projects',
        'search_items' => 'Search Projects Categories',
        'all_items' => 'All Projects Categories',
        'parent_item' => 'Parent Project Category',
        'parent_item_colon' => 'Parent Project Category:',
        'edit_item' => 'Edit Project Category',
        'update_item' => 'Update Project Category',
        'add_new_item' => 'Add New Project Category',
        'new_item_name' => 'New Project Category',
    );

    $args = array(
        'hierarchical' => true,
        'rewrite' => array('slug' => 'projects'),
        'show_in_nav_menus' => true,
        'labels' => $labels
    );

    register_taxonomy('projectscategory', 'projects', $args);

    unset($labels);
    unset($args);
}

Notice the following line in the above code. In this line we are creating our own custom tag %projectscategory%.

<?php
 'rewrite' => array('slug' => 'projects/%projectscategory%', 'with_front' => false)

[space]

 

Need help adding taxonomy? Our experts use scalable code and ensure your website is optimized for fast loading speeds!

Let us help

 

Add Taxonomy Term To Permalink 

Now, we will write a program to replace this tag with appropriate term name in the permalink. To do so, we will have to use filter ‘post_type_link’. Below code will check for the category assigned to the project. If no category is assigned, then it will replace ‘%projectscategory% with ‘uncategorized’ in the permalink.

<?php
add_filter('post_type_link', 'projectcategory_permalink_structure', 10, 4);
function projectcategory_permalink_structure($post_link, $post, $leavename, $sample) {
    if (false !== strpos($post_link, '%projectscategory%')) {
        $projectscategory_type_term = get_the_terms($post->ID, 'projectscategory');
        if (!empty($projectscategory_type_term))
            $post_link = str_replace('%projectscategory%', array_pop($projectscategory_type_term)->
            slug, $post_link);
        else
            $post_link = str_replace('%projectscategory%', 'uncategorized', $post_link);
    }
    return $post_link;
}

[space]

Now you should be able to see the following link in the address bar in your browser for a project that you have categorized under Magento.

[pre]http://abc.com/projects/magento/your-categorized-project-name[/pre]
[space]

However, if you have not categorized the project permalink will look something like this.

[pre]http://abc.com/projects/uncategorized/your-uncategorized-project-name[/pre]
[space]

Are you getting 404 errors for project links??? No worries!

Just go to the Permalinks section in settings make sure the common settings in this section are not default and hit the ‘Save Changes’ button.

 

If you’re short on time or the DIY route seems overwhelming, our WordPress experts can help customize your site quickly while also making sure that it’s optimized for speed. You can get started by discussing your project with us!

Discuss your Project

 

Was this post helpful? Did I miss out on something? Do you want to know something more? If the answer to any of these questions is yes, then please write to me in the comments section.

Sumit Pore

Sumit Pore

8 Responses

  1. Hi, I have made all your suggestion but this not work for me. Give me 404 error.
    When you say …”Just go to Permalinks section in settings and make sure the common settings in this section is not default and hit ‘Save Changes’ button”…what do you mean?

  2. Thank you, it’s work!
    But how can i create a page with base(parent) taxonomy? The link will be like ‘projects/%projectscategory%’

  3. Hi, thanks for post

    Is this possible to remove ‘/uncategorized’ part for posts not in a category? and return just the base term and the post name : domain.com/base_term/post_url

    Thank you

  4. Thank you so much, was looking for a solution to a problem before I realized manipulating the permalink was the perfect solution.

  5. Hi, Sumit,
    Your code works great for me, but still, when I select a term and its sub-term, the URL does not change. In this case, it works great (forex – example.com/term-name/post-name). But when i choose term and its sub-term it still shows only the primary term in the url , not the term anf the subt-erm(Forex – example.com/term-name/post-name), it must show like this(example.com/term-name/sub-term-name/post-name).
    kindly help.
    Thanks in advance.

  6. I use Custom taxonomy = ABC which have term like “a1, b1, c1…”. Now I want my posts’ permalinks structure is like this: abc.com/a1/post-1 and abc.com/c1/post-2.

    I set Custom Structure in Permalink = /%ABC%/%postname% but it did not work.

    Can you guide me a proper way to achieve my need?

    Many thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

WordPress Development

Custom WordPress Solutions, for You

LearnDash Development

Custom LearnDash Solutions, for You

WooCommerce Development

Custom WooCommerce Solutions, for You

WordPress Plugins

Scale your WordPress Business

WooCommerce Plugins

Scale your WooCommerce Business

LearnDash Plugins

Scale your LearnDash Business

Label

Title

Subtext

Label

Title

Subtext

Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads