skip to Main Content

Suppose I have a post tag which have as term id 480, I’m trying to create a redirect using add_rewrite_rule, so far I did:

function term_custom_redirect()
{
    $referer_url = "en/tag/a-lange-sohne";
    add_rewrite_rule(
        "^$referer_url/?$",
        'index.php?p=' . 480,
        "top"
    );

    flush_rewrite_rules();
}
add_action('init', 'term_custom_redirect', 10, 0);

the code should add a rewrite for the term id 480, so when the user visit the following url: example.com/en/tag/a-lange-sohne/, the tag page associated to 480 should be loaded, but I get a 404, even though I added flush_rewrite_rules at the end (I also saved the permalink from the backend).

UPDATE:

The main issue here is that some post tag contains within the url -en, and I want remove it, eg:

example.com/en/tag/a-lange-sohne-en/

should become:

example.com/en/tag/a-lange-sohne/

the taxonomy is post_tag and is the default available in wordpress, so I doesn’t have created any new taxonomy:

enter image description here

I though that my initial solution would work, but for some reason doesn’t. I also tried a new hook that should handle the job:

function update_term_link($permalink, $tag)
{
    if (strpos($permalink, '-en') !== false) {
        $permalink = str_replace('-en', '', $permalink);
    }

    return $permalink;
}

add_filter('tag_link', 'update_term_link', 10, 2);

but it doesn’t work either (I’ve refreshed the permalink always).

NB: using the tag_link hook I can see the new permalink structure correctly, it is simply not accessible with 404 error.

2

Answers


  1. Chosen as BEST ANSWER

    Based on the answer provided by @cabrerahector I was able to fix the problem, but in my case I have to remove the en part from $referer_url, so the final code looks like:

    $referer_url = str_replace('/en/', '', $referer_url);
    
    add_rewrite_rule(
        "^$referer_url?$",
        'index.php?tag=' . $term->slug,
        "top"
    );
    

  2. This should work:

    function term_custom_redirect()
    {
        $referer_url = "en/tag/a-lange-sohne";
        $tag_id = 480;
        $tag = get_term($tag_id, 'post_tag');
    
        if ( $tag ) {
            add_rewrite_rule(
                "^{$referer_url}/?$",
                'index.php?tag=' . $tag->slug,
                "top"
            );
    
            flush_rewrite_rules();
        }
    }
    add_action('init', 'term_custom_redirect', 10, 0);
    

    Here we’re using the tag parameter to ask WordPress to find the tag archive page by slug.

    The function uses get_term() to get the tag by ID (in your case, the ID is 480) and then we can use that information to retrieve the tag object, including its slug. This is good because if the tag gets renamed it doesn’t affect our code as the ID will remain the same.

    Screenshot of rewrite rule in effect

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search