skip to Main Content

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

Answers


  1. Chosen as BEST ANSWER

    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');
    

  2. 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;
    }
    

    }

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