是否使固定链接具有自定义格式?

时间:2016-03-26 作者:CodeAllDay

例如:

www.abc.com/ConstantCustomString-PostTitle-ConstantCustomString/

我怎样才能做到这一点,这有可能吗?我尝试在网上搜索,但没有任何问题答案指定如何进行上述更改?

1 个回复
最合适的回答,由SO网友:Prasad Nevase 整理而成

请参见下文。这将解决您将来发布的所有帖子的问题。我试过这个代码。但为了安全起见,请在尝试或启动转移之前备份数据库。

function custom_unique_post_slug( $slug, $post_ID, $post_status, $post_type ) {

    $post = get_post($post_ID); 

    /* Set a flag to know if the post slug is already updated to required format */

    $is_slug_updated = get_post_meta( $post->ID, \'is_slug_updated\' ); 

    /* define our two constant strings. You may change this to actual constants. */ 
    $first_const_str = "ConstantCustomString-";
    $second_const_str = "-ConstantCustomString";


    /* Check our flag and check post type is post and check if post is being published */
    if ( $post->post_type == \'post\' && $post->post_status == \'draft\' ) {        

        $slug = ucwords( str_replace("-", " ", $slug ) ) ;          
        $slug = str_replace( " ", "", $slug );    
        $slug = $first_const_str . $slug . $second_const_str;

        /* Update flag to to true */

        update_post_meta( $post->ID, \'is_slug_updated\', TRUE);        
    }

    /* here we are checking if post is already published then no need to update the slug */

    if( $post->post_type == \'post\' && $post->post_status == \'publish\' ) {

        $slug = $post->post_name;
    }    

    return $slug;
}

add_filter( \'wp_unique_post_slug\', \'custom_unique_post_slug\', 10, 4 );

相关推荐

Force pretty permalinks?

我正在构建一个插件,该插件将用于单个站点,并依赖于add_rewrite_rule 要工作,需要打开永久链接。打开它们并不困难,因为它只是一个站点,但我担心其中一个管理员可能会在不知道自己在做什么的情况下关闭它,并破坏该站点。如何以编程方式强制保持漂亮的永久链接?