我正在努力更改自定义帖子类型的永久链接,以在帖子 ID 之前包含分类法。我能够在 URL 中显示分类法,但是当我转到该页面时,我收到 404 错误。看起来永久链接的结构是正确的,但是帖子的位置与数据库位置不同步。
感谢任何帮助,并提前致谢!
一些注意事项:
代码
function change_permalink( $link, $post ) {
if ( ‘custom-post-type-name’ == get_post_type( $post ) ) {
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, ’taxonomy-name’);
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'no-taxonomy-listed’;
return str_replace('%tax%', $taxonomy_slug, $link);
}
return $link;
}
add_filter( 'post_type_link', ‘change_permalink’, 10, 2 );
想通了。需要 wp_rewrite:
add_action( 'wp_loaded', 'urban_permastructure' );
function urban_permastructure($post) {
if ( 'custom-post-type-name' == get_post_type( $post ) ) {
global $wp_rewrite;
$structure = '/cat/%tax%';
$wp_rewrite->add_rewrite_tag("%tax%", '([^/]+)', "tax-type=");
$wp_rewrite->add_permastruct('tax-type', $structure, false);
}
}