graham73may
11/1/2018 - 9:09 AM

Rewrite the posts (News) URL instead of setting the base that is applied to all CPTs

<?php
/**
 * Rewrite the posts (News) URL instead of setting the base that is applied to all CPTs
 *
 * @param $url
 * @param $post
 *
 * @return string|void
 */
function permalink_rewrite_to_news($url, $post)
{

    $post_type = get_post_type($post);
    if ($post_type === 'post') {
        $url = home_url('/news/' . $post->post_name . '/');
    }

    return $url;
}

add_filter('post_link', 'permalink_rewrite_to_news', 10, 2);

function add_news_rewrites($wp_rewrite)
{

    $wp_rewrite->rules = [
                             'news/([^/]+)/?$' => 'index.php?name=$matches[1]'
                         ] + $wp_rewrite->rules;

    return $wp_rewrite->rules;
}

add_action('generate_rewrite_rules', 'add_news_rewrites');