我刚刚设法重写了我的自定义帖子类型的URL永久链接结构,这种结构正如我想要的那样工作,但是由于添加了这些重写,我的博客文章开始转到404页面。
在我的functions.php文件中我有:
'rewrite' => array( 'slug' => '%companies%/projects', 'with_front' => false),
这是在我注册的自定义帖子类型中。
在我的functions.php的底部,我有这个片段:
function wpa_show_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'projects' ){
$terms = wp_get_object_terms( $post->ID, 'companies' );
if( $terms ){
return str_replace( '%companies%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );
我看不出这会影响我的帖子的原因?我通过管理员保存了永久链接。
答案 0 :(得分:0)
我之前在我的网站上做过类似的事情,所以我尝试重写我的代码以遵循你的结构,但你应该看看变量并用你的数据替换custompost和custompost-types。
最初发布在我的博客中:https://windowspros.ru/url-rewrites-custom-post-type-permalinks-wordpress/
// REMOVE OLD PERMALINKS IF EXSIT
add_action( "after_setup_theme", 'custom_remove_permalink', 1);
function custom_remove_permalink(){
remove_action( "after_setup_theme", 'active_permalinks');
}
// CREATE CUSTOM RULES
add_action( "after_setup_theme", 'custom_active_permalinks');
function custom_active_permalinks() {
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag("%custompost%", '([^/]+)', "custompost=");
$wp_rewrite->add_rewrite_tag( "%custompost-type%", '(.+?)', "custompost-type=" );
$wp_rewrite->add_rewrite_tag( "%companies%", '(.+?)', "companies=" );
$rewrite_args = array();
$rewrite_args['walk_dirs'] = false;
add_rewrite_rule( '([^/]+)/projects/?$', 'index.php?category_name=$matches[1]&post_type=custompost', 'top' );
$wp_rewrite->add_permastruct('custompost', '%companies%/projects/%custompost%', $rewrite_args);
}
// Make sure that all links on the site, include the related texonomy terms
add_filter( 'post_type_link', 'custom_custompost_permalink', 10, 2 );
function custom_custompost_permalink( $permalink, $post ) {
if ( $post->post_type !== 'custompost' ) {
return $permalink;
}
$companies = get_post_meta($post->ID, 'company', true );
if ( ! $companies ) {
$permalink = str_replace( '%companies%', 'defaultvalue', $permalink );
} else {
$permalink = str_replace( '%companies%', $companies , $permalink );
}
$terms = wp_get_post_terms($post->ID, 'custompost-type', array( 'orderby' => 'parent', 'order' => 'DESC' ));
if ( ! $terms ) {
$permalink = str_replace( '%custompost-type%', '_yoast_wpseo_primary_category', $permalink );
} else {
$permalink = str_replace( '%custompost-type%', $terms[0]->slug , $permalink );
}
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
if ( ! $author ) {
$permalink = str_replace( '%author%', 'author', $permalink );
} else {
$permalink = str_replace( '%author%', $author , $permalink );
}
return $permalink;
}