wordpress 自定义文章类型的固定链接

Auth:admin Date:2022-06-16 19:11:01 Cat:技术笔记


自定义文章类型无法在后台设置固定链接格式,可以在 functions.php 中通过代码来实现。代码如下:

<?php
/**
 * 实现 solution 文章类型的 URL 重写
 */
add_filter('post_type_link', 'custom_solution_link', 1, 3);
function custom_solution_link($link, $post) {
    if ($post->post_type == 'solution') {
        return home_url('solution/' . $post->ID . '.html');
    } else {
        return $link;
    }
}

add_action('init', 'custom_solution_rewrites_init');
function custom_solution_rewrites_init() {
    add_rewrite_rule(
        'solution/([0-9]+)?.html$',
        'index.php?post_type=solution&p=$matches[1]',
        'top'
    );
}

比较重要的一点:

代码添加完成后,一定要在后台 “ 固定链接设置” 页面,点击一下 “保存更改” 按钮才能生效!!

标签: