0

How do can I redirect the following URL to the next URL? It essentially should remove the ID part (this is a post tag URL).
http://wpsoup.test/tag/88/koffie/ -> http://wpsoup.test/tag/koffie/.

I've tried the following code functions to reverse create the URLs (they're from a website that uses an SPA as frontend and WordPress as backend, which means I need to reverse this behaviour because most, if not all, posts have a link with these kind of URLs), but they are not working (even after permalink flush). Is it only possible to do this with .htaccess?

function replace_tag_link($taglink, $tag_id) {
    $tag = get_tag($tag_id);
    $tag_name = $tag->slug;
    return str_replace($taglink, $tag_name, "$tag_id/$tag_name");
}
add_filter('tag_link', 'replace_tag_link', 10, 2);

// and...

function replace_tag_link($qv) {
    if (array_key_exists('tag', $qv)) {
        $tag = get_term_by('name', $qv['tag'], 'post_tag');
        $qv['tag'] = "{$tag->term_id}/{$qv['tag']}";
    }
}
add_filter('request', 'replace_tag_link', 10, 1);

1 Answer 1

0

I've fixed it with the following code:

/**
 * Redirect '/tag/[0-9]/{tag_name}/' to the correct tag.
 */
add_filter('request', function($qv) {
    if (array_key_exists('category_name', $qv) && preg_match('/(tag\/)([0-9]*)/', $qv['category_name'])) {
        $qv = [
            'tag' => $qv['name']
        ];
    }

    return $qv;
});

I'm not sure if this is the right way, but it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.