See: https://wordpress.org/support/article/using-permalinks/
By default, when someone sets their permalink structure to:
/%category%/%postname%/
Post URLs appear like so:
https://example.com/**abc**/some-cool-post/
ABC merely represents the first category of potentially several selected for the post, but unlikely the most appropriate.
I've made it so that my writers can select which category should be most prominent, which is saved as post meta for each post, and can be output with the variable $prominent_category
.
I would like to automatically replace %category%
with $prominent_category
in the slug, without the need of registering an additional taxonomy or doing anything else that might be overkill, so that whatever the author sets as their prominent category, say Pizza, that the new structure for the post appears as so:
https://example.com/**pizza**/some-cool-post/
Are either category_rewrite_rules
or post_link_category
the right choice, or should I be going down a different path?
if ( $prominent_category = get_post_meta( get_the_ID(), 'prominent_cat', true ) ) {
echo esc_html( str_replace( ' ', '-', strtolower( $prominent_category ) ) );
}
Full attempt:
add_filter( 'post_link_category', 'prominent_link_category', 10, 3 );
function prominent_link_category( $cat, $cats, $post ) {
if ( $prominent_primary_cat = get_post_meta( get_the_ID(), 'prominent_primary', true ) ) {
$cat = get_term_by( 'name', esc_html( str_replace( ' ', '-', strtolower( $prominent_primary_cat ) ) ), 'category' );
} else {
$category = get_the_category();
$cat = esc_attr( $category[0]->cat_slug );
}
return $cat;
}
$prominent_category
a global variable; if so, where/when/how is it defined? Or isprominent_category
the meta key? But yes, you'd want to use thepost_link_category
hook to filter the%category%
replacement value.prominent_cat
contain the category name (e.g.foo cat
), slug (e.g.foo-cat
) or ID (e.g.123
)?