自定义POST类型固定链接:仅使用%post_id%和删除%postname%

时间:2015-07-24 作者:lorem monkey

我在Wordpress中创建了一个自定义的帖子类型,效果很好。我唯一需要解决的是这个CTP创建的永久链接。

我目前拥有:

example.com/<custom-post-name>/<post-id>/<postname>/

I want it to only display the post-id:

example.com/<custom-post-name>/<post-id>/
自定义帖子类型已注册到:

function create_post_type_mycustomname() {
    $args = array(
        \'capability_type\' => \'post\',
        \'has_archive\' => \'mycustomname\',
        \'rewrite\' => array(
            \'slug\' => \'/mycustomname/%post_id%\',
            \'feeds\' => false
        )
    );

    register_post_type(\'ctp_mycustomname\', $args);
}
add_action(\'init\', \'create_post_type_mycustomname\');
以及%post_id 在slug中,将替换为以下内容:

function custom_post_mycustomname_link($post_link, $post = 0, $leavename = false) {
    if($post->post_type == \'ctp_mycustomname\') {
        return str_replace(\'%post_id%\', $post->ID, $post_link);
    }
    else {
        return $post_link;
    }
}
add_filter(\'post_type_link\', \'custom_post_mycustomname_link\', 1, 3);
有没有关于如何从这些URL中删除postname的提示?

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

I found the answer myself - so here is the update to above problem:

Custom post type registration:

function create_post_type_mycustomname() {
    $args = array(
        \'capability_type\' => \'post\',
        \'has_archive\' => \'mycustomname\',
        \'rewrite\' => array(
            \'slug\' => \'/mycustomname\',
            \'feeds\' => false
        )
    );

    register_post_type(\'ctp_mycustomname\', $args);
}
add_action(\'init\', \'create_post_type_mycustomname\');

Change the links:

function mycustomname_links($post_link, $post = 0) {
    if($post->post_type === \'ctp_mycustomname\') {
        return home_url(\'mycustomname/\' . $post->ID . \'/\');
    }
    else{
        return $post_link;
    }
}
add_filter(\'post_type_link\', \'mycustomname_links\', 1, 3);

Add the correct rewrites rules:

function mycustomname_rewrites_init(){
    add_rewrite_rule(\'mycustomname/([0-9]+)?$\', \'index.php?post_type=ctp_mycustomname&p=$matches[1]\', \'top\');
}
add_action(\'init\', \'mycustomname_rewrites_init\');

Flush rewrite-rules in Wordpress backend afterwards and you are good to go!

结束

相关推荐

Pretty Permalinks

我创建了自己的搜索功能,基本上可以找到与输入的邮政编码最近的商店。我的搜索URL当前如下所示http://www.example.com/stores?searchTerm=London, 这并不是真正的SEO友好。我希望我的URL采用以下格式-http://www.example.com/stores/London, 然而,由于我缺乏WordPress URL重写工作的知识,我正在努力解决这个问题,希望能得到一些帮助来解决这个问题。Stores是一个循环显示结果的页面。如果有人对如何做到这一点有任何想法