我正在努力用自定义分类法设置自定义permalink结构。我在这里阅读了许多问题/答案,但我无法将其付诸实施(最令人沮丧的是,我不知道如何调试并自己找到问题)。非常感谢您的帮助!
What you need to know
<我有一个自定义的帖子类型,叫做items
items
有两种自定义分类法:types
和locations
. onetype
和multiple (1+)locations
item
:http://domain.com/type/location
然而,我只想在这个链接结构中使用第一个位置术语。
我还没有尝试实现/location
链接结构的一部分(我想这有点复杂),因为我已经在努力/type/
部分因此,我的代码目前看起来是这样的,这不会对我的永久链接产生任何更改:
in a plugin
register_post_type( \'item\',
array(
\'labels\' => $labels,
\'supports\' => array( \'title\', \'editor\', \'thumbnail\', \'comments\'),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => true,
\'menu_icon\' => plugins_url( \'/img/icon.png\'),
\'menu_position\' => 42,
\'categories\' => array( ),
)
);
register_taxonomy( \'types\', \'item\', array(
\'labels\' => $item_types_labels,
\'hierarchical\' => true,
\'query_var\' => \'type\',
\'rewrite\' => true,
\'public\' => true,
\'show_ui\' => true,
) );
in functions.php
add_filter(\'post_link\', \'types_permalink\', 10, 3);
add_filter(\'post_type_link\', \'types_permalink\', 10, 3);
function types_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, \'%types%\') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, \'types\');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = \'no-type\';
return str_replace(\'%types%\', $taxonomy_slug, $permalink);
}
我将永久链接结构设置为自定义结构/%types%/%postname%/
. 我的URL仍然如下所示domain.com/item/postname
.还有:无论我做什么/item/
(例如。domain.com/this-doesn-make-sense-to-me/postname
), 我被重定向到domain.com/item/postname
.