开发模板的过程中,难免会需要添加自定义文章类型,但是默认的链接结构都是类似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插件:
下载列表
原文链接:https://www.dqzy.cn/2025/05/18/603.html,转载请注明出处。
1、本站所有源码资源(包括源代码、软件、学习资料等)仅供研究学习以及参考等合法使用,请勿用于商业用途以及违法使用。如本站不慎侵犯您的版权请联系我们,我们将及时处理,并撤下相关内容!
2、访问本站的用户必须明白,本站对所提供下载的软件和程序代码不拥有任何权利,其版权归该软件和程序代码的合法拥有者所有,请用户在下载使用前必须详细阅读并遵守软件作者的“使用许可协议”,本站仅仅是一个学习交流的平台。
3、如下载的压缩包需要解压密码,若无特殊说明,那么文件的解压密码则为:www.dqzy.cn。
4、点启资源网是一个免费且专业分享网站源码、图片素材、特效代码、教程文章、站长工具的平台。我们努力给站长提供好的资源!
评论0