为什么WordPress在帖子/页面视图上添加重复的数字slug?

Ren*_*ené 5 php wordpress

这是我在这里的第一篇文章,所以我提前为任何不幸事件道歉.

我一直在寻找想要解决这个问题的几个小时,但我似乎无法理解为什么会这样.

我正在设置的网站是一个子网站(不是多站点意义上的,而是一个具有相同品牌的独立网站/域名).我网站上的一些帖子将来自父/主站点(但将通过复制粘贴制作为新帖子),我希望原始文章ID作为永久链接的一部分.

例如http://www.example.com/hello-world/12345/,其中12345是父/主站点上文章的文章ID.

为此,我在帖子中添加了一个自定义字段,我可以在其中添加原始文章的文章ID external_article_id作为字段名称.然后,我尝试使用以下代码操作永久链接:

add_filter('post_link', 'append_custom_permalink', 10, 2);

function append_custom_permalink($url, $post) {
    $newurl = $url;

    if ($post->post_type == 'post') {
        $custom = get_post_custom_values('external_article_id', $post->ID);
        if (!empty($custom))
            $newurl = $url . $custom[0] . '/';
    }

    return $newurl;
}
Run Code Online (Sandbox Code Playgroud)

每当我将永久链接输出到帖子时,它就会在编辑器和网站上完全按照我的要求显示.但是,当我点击链接或手动输入地址时,我会自动重定向到http://www.example.com/hello-world/12345/12345/.它复制了额外的数字slug,当我$custom[0]用硬编码的数值替换时也会发生这种情况.这适用于所有帖子,我的永久链接结构(在设置中)设置为/%postname%/.

我甚至尝试将固定链接结构设置为/%postname%/%ext_article_id%/并替换%ext_article_id%$custom[0],但具有完全相同的结果.我也尝试在另一个WordPress网站上使用相同的代码,除了这次使用页面而不是帖子,也有完全相同的结果.

理想情况下,我想使用类似的东西add_query_arg($custom[0], '', get_permalink($post->ID));,但省略随之而来的问号.

有人可以向我解释为什么会发生这种情况,以及我如何规避这一点?我是否需要使用其他过滤器,或者我该如何处理?

先感谢您!

Mak*_*ida 3

为了使这项工作正常进行,您还需要让 WordPress 了解rewrite_tag并通过 指定额外的永久链接结构add_permastruct。下面的代码应该可以解决这个问题:

function append_custom_permalink( $post_link, $post ) {
    if( $post->post_type == 'post' ) {
        $custom = get_post_custom_values( 'external_article_id', $post->ID );
        if( ! empty($custom) ) {
            $post_link = $post_link.$custom[0].'/';
        }
    }
    return $post_link;
}
add_filter('post_link', 'append_custom_permalink', 10, 2);

function sof_30058470_posts_rewrite() {
    add_rewrite_tag('%external_article_id%', '([^/]+)', 'external_article_id=');
    add_permastruct('external_article_id', '/%year%/%monthnum%/%day%/%postname%/%external_article_id%/', false);
}
add_action('init', 'sof_30058470_posts_rewrite', 10, 0);
Run Code Online (Sandbox Code Playgroud)

添加代码后,请确保在“设置”->“永久链接”中重新保存永久链接结构。您可能还需要刷新/清除浏览器缓存。