唯一固定链接结构上的邮政名为自定义帖子类型附加“-2”。我怎么才能让这件事不再发生?

时间:2022-01-19 作者:EmilyH

“我有一个自定义的帖子类型”;“事件”;这已经重写/永久链接修改到位,以便在URL中包含年份和月份(这些来自ACF字段)。这非常有效,但如果我们有两个事件使用相同的;“slug”;然后WordPress会强制新邮件具有唯一的postname/slug。我在谷歌上搜索这个已经有点太久了,但真的找不到解决方法。

正在发生的事情的示例(其中“saint louis”是从标题中提取的postname/slug):

https://example.com/events/2022/january/saint-louis/

https://example.com/events/2022/february/saint-louis-2/

我想看到的是:

https://example.com/events/2022/january/saint-louis/

https://example.com/events/2022/february/saint-louis/

我得到的最接近修复的可能是完全删除postname:Custom post type permalink: only use %post_id% and remove %postname%

但是:该修复程序包含了帖子ID,我不想在URL中使用它。这里有人有什么想法吗?我也考虑过使用另一个自定义字段(代表“city”),这样“saint louis”就不会从postname中删除,但我真的不知道从哪里开始。

我还尝试打开/关闭层次结构,以及;第“”页;但是没有运气。

我的当前设置:

function wdacRegisterEventsPostType() {

/**
 * Post Type: Events.
 */

add_rewrite_tag( \'%wdac_year%\', \'([^&]+)\' );
add_rewrite_tag( \'%wdac_month%\', \'([^&]+)\' );

$labels = [
    "name" => __( "Events", "wdac" ),
    "singular_name" => __( "Event", "wdac" ),
];

$args = [
    "label" => __( "Events", "wdac" ),
    "labels" => $labels,
    "description" => "",
    "public" => true,
    "publicly_queryable" => true,
    "show_ui" => true,
    "show_in_rest" => false,
    "rest_base" => "",
    "rest_controller_class" => "WP_REST_Posts_Controller",
    "has_archive" => \'events\',
    "show_in_menu" => true,
    "show_in_nav_menus" => true,
    "delete_with_user" => false,
    "exclude_from_search" => false,
    "capability_type" => "post",
    "map_meta_cap" => true,
    "hierarchical" => false,
    "rewrite" => [
        "slug" => "/events/%wdac_year%/%wdac_month%",
        "with_front" => false
    ],
    "query_var" => true,
    "menu_position" => 5,
    "menu_icon" => "dashicons-calendar-alt",
    "supports" => [ "title", "editor", "thumbnail" ],
];

register_post_type( "events", $args );
}
add_action( \'init\', \'wdacRegisterEventsPostType\' );


// Modify events permalink
function wdacModifyEventsURL($permalink, $post) {
$yearMask = \'%wdac_year%\';
$monthMask = \'%wdac_month%\';

// Exit early.
if( strpos($permalink, $yearMask) === false && strpos($permalink, $monthMask) === false ) {
    return $permalink;
}

// Another exit early
if (!function_exists(\'get_field\')) {
    return $permalink;
}

$startDate = strtotime(get_field(\'wdac_event_start_date\', $post->ID));

$year = date("Y", $startDate);
$month = strtolower(date("F", $startDate));

return str_replace([$yearMask,$monthMask], [$year, $month], $permalink );
}
add_filter(\'post_type_link\', \'wdacModifyEventsURL\', 1, 3);

1 个回复
最合适的回答,由SO网友:Sébastien Serre 整理而成

默认情况下,WordPress不允许使用2个相同的slug,因为如果您将permalink结构更改为自定义结构,则您应该能够在您的情况下拥有:

相关推荐