apply_filters( 'pre_term_link', string $termlink, WP_Term $term ) is a WordPress PHP filter that allows you to modify the permalink structure of a term before the actual token replacement occurs. This is useful when you want to customize how the term links are generated for your website.
Usage
To use this filter, you need to add it to your theme’s functions.php
file or a custom plugin. Here’s a code example:
function custom_pre_term_link( $termlink, $term ) { // Your custom code goes here return $termlink; } add_filter( 'pre_term_link', 'custom_pre_term_link', 10, 2 );
Parameters
- $termlink (string)
- The permalink structure for the term’s taxonomy.
- $term (WP_Term)
- The term object.
Examples
Add a prefix to category permalinks
function add_category_prefix( $termlink, $term ) { if ( 'category' === $term->taxonomy ) { $termlink = '/prefix' . $termlink; } return $termlink; } add_filter( 'pre_term_link', 'add_category_prefix', 10, 2 );
This code adds a /prefix
to the permalink structure of categories. For example, if the original permalink was /category/news
, it will become /prefix/category/news
.
Remove the taxonomy base slug from custom taxonomy permalinks
function remove_taxonomy_base_slug( $termlink, $term ) { if ( 'custom_taxonomy' === $term->taxonomy ) { $termlink = str_replace( '/custom_taxonomy', '', $termlink ); } return $termlink; } add_filter( 'pre_term_link', 'remove_taxonomy_base_slug', 10, 2 );
This code removes the custom taxonomy base slug from its permalinks. If the original permalink was /custom_taxonomy/term
, it will become /term
.
Make term permalinks lowercase
function make_term_permalink_lowercase( $termlink, $term ) { return strtolower( $termlink ); } add_filter( 'pre_term_link', 'make_term_permalink_lowercase', 10, 2 );
This code changes the term permalinks to lowercase. For example, if the original permalink was /Category/News
, it will become /category/news
.
Append term ID to the term permalinks
function append_term_id( $termlink, $term ) { return $termlink . '-' . $term->term_id; } add_filter( 'pre_term_link', 'append_term_id', 10, 2 );
This code appends the term ID to the permalink structure. If the original permalink was /category/news
, it will become /category/news-123
where 123
is the term ID.
Change term permalinks based on the parent term
function change_term_permalink_based_on_parent( $termlink, $term ) { if ( $term->parent ) { $parent_term = get_term( $term->parent, $term->taxonomy ); $termlink = str_replace( $parent_term->slug, 'parent-' . $parent_term->slug, $termlink ); } return $termlink; } add_filter( 'pre_term_link', 'change_term_permalink_based_on_parent', 10, 2 );
This code changes the term permalinks to include a parent taxonomy.