给 WordPress 文章的固定链接添加前缀

给 WordPress 文章添加前缀,虽然可以在后台“设置”-“固定链接”中轻松的完成,但此方法会在所有的页面里添加这个前缀,这样不利于网站不同文章类型的区分,以下我整理了三种通过代码实现的方式,单独为默认的文章类型添加前缀。

实现效果:
原文章URL: https://puji.design/sample-name
更改后文章URL: https://puji.design/blog/sample-name

方法1:

注:此方法修改后,在编辑文章页面中,无法重新自定义该文章 URL 别名

//Wordpress 文章固定链接添加前缀
function add_rewrite_rules( $wp_rewrite )
{
    $new_rules = array(
        'blog/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
    );

    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules'); 

function change_blog_links($post_link, $id=0){

    $post = get_post($id);

    if( is_object($post) && $post->post_type == 'post'){
        return home_url('/blog/'. $post->post_name.'/');
    }

    return $post_link;
}
add_filter('post_link', 'change_blog_links', 1, 3);

方法2:

此方法是直接将原有的 post 文章类型进行修改,但比较烦人的是会在后台重复出现两次“文章”的目录,并且两个文章目录同时工作,强迫症的朋友慎选。

function redefine_post() {
    register_post_type( 'post', array(
        'labels' => array(
            'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
        ),
        'public'  => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        '_builtin' => false,
        '_edit_link' => 'post.php?post=%d',
        'capability_type' => 'post',
        'map_meta_cap' => true,
        'hierarchical' => false,
        'rewrite' => array( 'slug' => 'blog' ),
        'query_var' => false,
        'has_archive' => true,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
        'show_in_rest' => true,
    ) );
}
add_action( 'init', 'redefine_post', 1 );

参考地址:https://stackoverflow.com/questions/7285532/url-prefix-for-posts-wordpress

方法3:

最优方案,同时解决了前面两种方法的问题,参考地址:https://www.bobz.co/add-blog-prefix-permalink-structure-blog-posts

//Wordpress 文章固定链接添加前缀
function puji_create_new_url_querystring() {
    add_rewrite_rule(
        'blog/([^/]*)$',
        'index.php?name=$matches[1]',
        'top'
    );

    add_rewrite_tag('%blog%','([^/]*)');
}
add_action('init', 'puji_create_new_url_querystring', 999 );

function puji_append_query_string( $url, $post, $leavename ) {

	if ( $post -> post_type != 'post' )
        	return $url;

	if ( false !== strpos( $url, '%postname%' ) ) {
        	$slug = '%postname%';
	}
	elseif ( $post->post_name ) {
        	$slug = $post->post_name;
	}
	else {
		$slug = sanitize_title( $post->post_title );
	}
    
	$url = home_url( user_trailingslashit( 'blog/'. $slug ) );

	return $url;
}
add_filter( 'post_link', 'puji_append_query_string', 10, 3 );

function puji_redirect_old_urls() {

	if ( is_singular('post') ) {
		global $post;

		if ( strpos( $_SERVER['REQUEST_URI'], '/blog/') === false) {
		   wp_redirect( home_url( user_trailingslashit( "blog/$post->post_name" ) ), 301 );
		   exit();
		}
	}
}
add_filter( 'template_redirect', 'puji_redirect_old_urls' );