Loading
0

wordpress 修改自定义文章类型的固定链接结构

开发模板的过程中,难免会需要添加自定义文章类型,但是默认的链接结构都是类似forum/标题 这种结构,可能对搜索引擎不友好,所以我们需要做些修改,下面有两种方法。将代码贴进主题的functions.php里,然后更新下固定链接即可!

方法一:

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

方法二:

add_action('init', 'custom_blog_rewrite');
function custom_blog_rewrite() {
 global $wp_rewrite;
 $queryarg = 'post_type=blog&p=';
 $wp_rewrite->add_rewrite_tag('%qid%', '([^/]+)', $queryarg);
 $wp_rewrite->add_permastruct('blog', '/blog/%qid%.html', false);
}
 
add_filter('post_type_link', 'custom_blog_permalink', 1, 3);
function custom_blog_permalink($post_link, $post = 0) {
 global $wp_rewrite;
 if ( $post->post_type == 'blog' ){
 $post = &get_post($id);
 if ( is_wp_error( $post ) )
 return $post;
 $newlink = $wp_rewrite->get_extra_permastruct('blog');
 $newlink = str_replace("%qid%", $post->ID, $newlink);
 $newlink = home_url(user_trailingslashit($newlink));
 return $newlink;
 } else {
 return $post_link;
 }
}

不过,以上两种方法都会出现一个问题,那就是发表评论后报404,所以模板兔在这里推荐使用插件来解决这个问题。

custom post type permalinks WordPress插件

下载列表

特别声明:1、本站仅提供源码学习下载,使用者需具备一定的技术基础,源码费用仅为站长辛苦整理费,不代表源码自身价值也不包含任何服务,如需完美运营请到官方购买。如需搭建、二开、bug修复等服务需额外收费,如果源码侵犯了您的利益请联系客服处理! 2、用户必须遵守《计算机软件保护条例(2013修订)》第十七条:为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。鉴于此条例,用户从本平台下载的全部源码(软件)仅限学习研究,未经版权归属者授权不得商用,若因商用引起的版权纠纷,一切责任均由使用者自行承担,本平台所属公司及其雇员不承担任何法律责任。本站邮箱:weituiw@qq.com