如何设置固定链接(WordPress自定义内容模型)

Wordpress5个月前更新 SUYEONE
835 0 0

在之前的教程中,我们成功创建了一个名为“商城”的WordPress自定义文章类型,并且使其在后台菜单中显示,同时,文章在前端也能正常展示。然而,我们注意到一个细节问题:文章的前端URL并不美观,尤其是对于包含中文标题的文章,翻译后的URL显得冗长且不太友好,例如:这样的URL格式显然不够雅观,也不利于网站搜索引擎优化。造成这种情况的原因在于,`register_post_type()` 函数默认生成的URL结构为 ‘post-slug/postname’,即自定义文章类型加文章标题。由于我们的文章标题是中文,导致了这一不太理想的URL形式。

为了解决这个问题,我们需要调整文章的固定链接结构,使其更简洁且有利于seo。`register_post_type()` 提供了如 `rewrite` 和 `slug` 等参数来定制URL。在我们的情况中,我们想要将URL改为以文章ID代替文章标题,例如:Http://xxxxxxxxxx.com/book/33.htML。以下代码展示了如何在主题的 `functions.php` 文件中实现这一改变:

“`php
add_filter(‘post_type_link’, ‘custom_book_link’, 1, 3);
function custom_book_link($link, $post = 0) {
if ($post->post_type == ‘book’) {
return home_url(‘book/’) . $post->ID . ‘.html’;
} else {
return $link;
}
}
add_Action(‘init’, ‘custom_book_rewrites_init’);
function custom_book_rewrites_init() {
add_rewrite_rule(‘book/([0-9]+)?.html$’, ‘index.php?book&p=$matches[1]’, ‘top’);
}
“`

这段代码仅适用于单一的自定义文章类型。如果你有多个自定义文章类型,可以采用以下通用的方法:

“`php
$my_types = array(
‘type1’ => ‘slug1’,
‘type2’ => ‘slug2’,
‘type3’ => ‘slug3’
);

add_filter(‘post_type_link’, ‘custom_book_link’, 1, 3);
function custom_book_link($link, $post = 0) {
global $my_types;
if (in_array($post->post_type, array_keys($my_types))) {
return home_url($my_types[$post->post_type] . ‘/’ . $post->ID . ‘.html’);
} else {
return $link;
}
}
add_action(‘init’, ‘custom_book_rewrites_init’);
function custom_book_rewrites_init() {
global $my_types;
foreach ($my_types as $k => $v) {
add_rewrite_rule($v . ‘/([0-9]+)?.html$’, ‘index.php?post_type=’ . $k . ‘&p=$matches[1]’, ‘top’);
}
}
“`

在这个例子中,我们有三个自定义文章类型,对应slug1、slug2和slug3。你需要确保这些slug与你在注册时使用的名称相匹配,它们将作为URL的前缀。

以上就是如何修改WordPress自定义文章类型的固定链接样式的方法,后续我们将继续探讨相关话题。

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!