The post_link_category WordPress PHP filter allows you to modify the category that gets used in the %category% permalink token.
Usage
add_filter('post_link_category', 'your_custom_function', 10, 3);
function your_custom_function($cat, $cats, $post) {
// your custom code here
return $cat;
}
Parameters
$catWP_Term: The category to use in the permalink.$catsarray: Array of all categories (WP_Term objects) associated with the post.$postWP_Post: The post in question.
More information
See WordPress Developer Resources: post_link_category
Examples
Change the category in permalink to a specific one
This example replaces the category in the permalink with a specific category named “News”:
add_filter('post_link_category', 'change_permalink_category', 10, 3);
function change_permalink_category($cat, $cats, $post) {
foreach ($cats as $category) {
if ($category->slug == 'news') {
return $category;
}
}
return $cat;
}
Use the lowest ID category for permalink
This example chooses the category with the lowest ID for the permalink:
add_filter('post_link_category', 'lowest_id_category', 10, 3);
function lowest_id_category($cat, $cats, $post) {
$lowest_cat = $cat;
foreach ($cats as $category) {
if ($category->term_id < $lowest_cat->term_id) {
$lowest_cat = $category;
}
}
return $lowest_cat;
}
Use the parent category for permalink
This example changes the permalink to use the parent category of the current category:
add_filter('post_link_category', 'parent_category_permalink', 10, 3);
function parent_category_permalink($cat, $cats, $post) {
if ($cat->parent) {
$parent_cat = get_category($cat->parent);
return $parent_cat;
}
return $cat;
}
Use the category with the most posts for permalink
This example selects the category with the most posts for the permalink:
add_filter('post_link_category', 'most_posts_category', 10, 3);
function most_posts_category($cat, $cats, $post) {
$most_posts_cat = $cat;
foreach ($cats as $category) {
if ($category->count > $most_posts_cat->count) {
$most_posts_cat = $category;
}
}
return $most_posts_cat;
}
Exclude a specific category from permalink
This example excludes a specific category named “Uncategorized” from the permalink:
add_filter('post_link_category', 'exclude_uncategorized', 10, 3);
function exclude_uncategorized($cat, $cats, $post) {
if ($cat->slug == 'uncategorized' && count($cats) > 1) {
foreach ($cats as $category) {
if ($category->slug != 'uncategorized') {
return $category;
}
}
}
return $cat;
}