W
W
WeReng2017-04-06 15:11:36
Apache HTTP Server
WeReng, 2017-04-06 15:11:36

How to make a redirect to the main wordpress page without duplicates?

Hello!
Please help me, is it possible to somehow redirect wordpress to the following form via htacess:
There is a post page
site.ru/category_name/post_name the site.ru/category_name/post_name page will open, but the url will remain like this site.ru/category_name/post_name/123
Please tell me how to make it so that there is a redirect to the main page, and all numbers are discarded?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TraiDeR, 2017-04-06
@WeReng

You can solve the problem of endless duplicate pages in wordpress by simply embedding the following code in your theme's functions.php:

global $posts, $numpages;

$request_uri = $_SERVER['REQUEST_URI'];

$result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches);

$ordinal = $result ? intval($matches[1]) : FALSE;

if(is_numeric($ordinal)) {

    // a numbered page was requested: validate it
    // look-ahead: initialises the global $numpages

    setup_postdata($posts[0]); // yes, hack

    $redirect_to = ($ordinal < 2) ? '/': (($ordinal > $numpages) ? "/$numpages" : FALSE);

    if(is_string($redirect_to)) {

    // we got us a phantom
    $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);

    // if page = 0 or 1, redirect permanently
    if($ordinal < 2) {
        header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
    } else {
        header($_SERVER['SERVER_PROTOCOL'] . ' 302 Found');
    }

    header("Location: $redirect_url");
    exit();

    }
}

Solution Source

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question