php – Custom permalink tag works for posts, redirects pages to home
My goal is to select a main tag to use as part of the URL structure for the standard post type. Since there is no way to choose a “main” tag from the default post taxonomy out of the box I’ve created post meta (via ACF) which gets all tags, allows the user to choose one, and assigns that as part of the URL.
So let’s say I have a post that has the tags rock, pop, and electronic. I use my ACF field to set the main tag as electronic, because I want my URL to be https://example.com/electronic/postname/. Using the post_link
filter and add_rewrite_tag()
I’ve added the main tag so that I can enter it on the permalinks admin screen. My custom permalink setup is now https://example.com/%main_tag%/%postname%/
.
This is working perfectly fine for normal posts, but now all of my pages are redirecting to the home page. I’d like my posts to have the /%main_tag%/
part of the URL without impacting the rest of the site in any way. Code snippets from functions.php are below.
function _themename_rewrites() {
add_rewrite_tag( '%main_tag%', '([^&]+)', 'main_tag=' );
add_rewrite_rule('^/([^/]*)/?','index.php?main_tag=$matches[1]','top');
}
add_filter( 'post_link', '_themename_filter_topic_post_link', 10, 2 );
function _themename_filter_topic_post_link( $permalink, $post ) {
if ( false === strpos( $permalink, '%main_tag%'))
return $permalink;
$main_tag_id = intval( get_post_meta( $post->ID, 'main_tag', true ) );
// Choose first selected tag if custom field not set
if ( empty( $main_tag_id) ) {
$main_tag_id = get_the_tags( $post->ID )[0]->term_id;
}
// Get slug from ID
$main_tag = get_term( $main_tag_id )->slug;
$main_tag = urlencode( $main_tag );
$permalink = str_replace( '%main_tag%', $main_tag, $permalink );
return $permalink;
}
I’ve been digging through tons of StackExchange questions very similar to this, but most related issues are with custom posts and taxonomies and any I’ve come across for default post types seem to have gone unanswered so any help is greatly appreciated.
Leave an answer