Yes, the post_link_category
hook is indeed what you would use to filter the %category%
replacement value in the permalink.
And here’s an example with prominent_cat
being the meta key and the value being the category name (e.g. Pizza Hut
), where I’m using get_term_by()
to get the category object/data:
add_filter( 'post_link_category', 'my_post_link_category', 10, 3 );
function my_post_link_category( $cat, $cats, $post ) {
$prominent_category = get_post_meta( $post->ID, 'prominent_cat', true );
if ( $term = get_term_by( 'name', $prominent_category, 'category' ) ) {
$cat = $term;
}
return $cat;
}
If the meta value is a term/category ID, then you can simply use get_term()
to get the category data:
add_filter( 'post_link_category', 'my_post_link_category', 10, 3 );
function my_post_link_category( $cat, $cats, $post ) {
$prominent_category = get_post_meta( $post->ID, 'prominent_cat', true );
if ( $prominent_category && term_exists( (int) $prominent_category ) ) {
$cat = get_term( $prominent_category );
}
return $cat;
}