首页 > WordPress > WordPress自定义分类下自定义文章类型URL结构修改办法

WordPress自定义分类下自定义文章类型URL结构修改办法

时间:2022年6月14日 分类:WordPress 浏览量:349

WordPress自定义文章类型的文章固定链接结构默认是http://域名/post_type/post_name,这样的格式,比如自定义文章类型是product,那么文章URL就是http://域名/product/文章别名,如果想要把固定链接更改为http://域名/post_type/post_id.html的格式怎么办?因为WordPress并没有在后台提供自定义文章类型的固定链接设置,因此需要通过代码或插件实现。

1、以product自定义文章类型为例,在当前主题的functions.php文件中添加以下代码:

add_filter('post_type_link', 'custom_product_link', 1, 3);
function custom_product_link( $link, $post = 0 ){
    if ( $post->post_type == 'product' ){
        return home_url( 'product/' . $post->ID .'.html' );
    } else {
        return $link;
    }
}
add_action( 'init', 'product_rewrites_init' );
function product_rewrites_init(){
    add_rewrite_rule(
        'product/([0-9]+)?.html$',
        'index.php?post_type=product&p=$matches[1]',
        'top' );
    add_rewrite_rule(
        'product/([0-9]+)?.html/comment-page-([0-9]{1,})$',
        'index.php?post_type=product&p=$matches[1]&cpage=$matches[2]',
        'top'
        );
}

提示:请把代码中的product替换为自己的自定义文章类型。

2、添加好代码后,进入网站后台——设置——固定链接,点击“保存更改”后,修改生效,如果不点击保存更改是不会生效的。

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签: