Wordpress重写slug = post_meta

时间:2016-01-13 08:09:55

标签: wordpress rewrite custom-post-type permalinks

此时我有2个自定义帖子类型项目,项目,在项目帖子中自定义字段用于附加项目帖子(自定义field save post_id)

我想在链接中使用附加的项目后名:

目前的链接结构:
域名/ {item-post-type-slug} / {item-name}

我想改变:
域/ {project-> post_name} / {item-name}

使用当前代码应该在post-type项目的每个保存/删除操作上刷新重写规则?

如何将旧链接结构重定向到新的?

add_action( 'init', 'add_rewrite_rules' );  
function add_rewrite_rules() {  

    $arg = array(
        'post_type' => 'projects',
        'no_conflict' => '1',
        'posts_per_page' => '-1'
    );

    $projects= new WP_Query($arg);

    while($projects->have_posts() ) : $projects->the_post();

        global $post;
        add_rewrite_rule(  $post->post_name.'/([^/]+)/?$', 'index.php?item=$matches[1]', 'top');

    endwhile;
} 

add_filter( 'post_type_link', 'custom_permalinks', 10, 2 );
function custom_permalinks( $permalink, $post ) {
    if ( $post->post_type !== 'item' )
        return $permalink;

    $project_id = get_field('project', $post->ID);
    $project = get_post($project_id);

    $new_permalink = str_replace("item", $project->post_name, $permalink);

    return $new_permalink;
}

使用

进行刷新重写规则
function flush_project_links( $post_id) {

if ( get_post_type( $post_id ) != 'projects' )
        return;

flush_rewrite_rules();

}
add_action('delete_post', 'flush_project_links', 99, 2);
add_action('save_post', 'flush_project_links', 99, 2);

但它只在第二次更新帖子

时起作用

更新: flush rewrite fixed:

function flush_project_links( $post_id) {

   if ( get_post_type( $post_id ) != 'projects' )
        return;

   add_rewrite_rules()
   flush_rewrite_rules();

}
add_action('delete_post', 'flush_project_links', 99, 2);
add_action('save_post', 'flush_project_links', 99, 2);

并删除 add_action(' init',' add_rewrite_rules');

0 个答案:

没有答案