WordPress设置

wordpress修改自定义文章类型文章URL结构的方法

发表于:2024-05-20 作者:WordPress设置编辑
编辑最后更新 2024年05月20日,wordpress自定义文章类型的文章固定链接结构默认是http://域名/post_type/post_name/格式,比如自定义文章类型是product,那么文章URL就是http://域名/pr

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、添加好代码后,进入网站后台--设置--固定链接,点击"保存更改"后,修改生效,如果不点击保存更改是不会生效的。

0