Permalinks and redirects

78 Views Asked by At

I would like to change the permalink from /%category%/%postname%/ to /%category%/%postname%-%post_id%/

How to set up a redirect correctly?

Tried setting it up through the Redirection plugin, but I don't know how to properly configure the rule.

Or maybe the function is easier to write?

2

There are 2 best solutions below

2
Harish Tewari On

Go to /wp-admin/options-permalink.php

Select Custom Structure and insert this rule.

/%category%/%postname%-%post_id%/

And save changes. After this use this

add_action('template_redirect', 'append_id_to_url');

function append_id_to_url() {
 if ( is_single() ) {
    global $wp;
    $current_url = home_url(add_query_arg(array(), $wp->request)); // Get the current URL
    $article_id  = get_the_ID();
    wp_redirect( $current_url . '-' . $article_id . '/' );
    exit;
}

}

0
W1ns On

I did this way

function rudr_post_permalink($url)
{
    $request_uri = urldecode($_SERVER['REQUEST_URI']);
    $the_slug = basename(parse_url($request_uri, PHP_URL_PATH));

    if ($the_slug)
    {
        $args = array(
            'name' => $the_slug,
            'post_type' => 'post',
            'post_status' => 'publish',
            'numberposts' => 1
        );
        $my_posts = get_posts($args);

        if ($my_posts):
            $post_url = get_post_permalink($my_posts[0]->ID);
            wp_redirect($post_url, 301);
            die();
        endif;

    }
}

add_filter('template_redirect', 'rudr_post_permalink');