首页 > 解决方案 > 在搜索中重写自定义帖子类型 URL

问题描述

我有一个网站,其中有一个自定义帖子类型(来自CoAuthors Plus的客座作者)。通过一个插件,我设法使自定义类型的“来宾作者”的帖子可以通过 WordPress 旧版搜索进行搜索。

现在,作者已正确显示在搜索结果中。虽然,它们链接到了错误的页面/?post_type=guest-author&p=2148,这会导致 404。

我希望能够获取 URL,对其进行解释,然后重定向到正确的页面(格式为/archives/author/name-surname/.

我试图让它与重写 URL 一起工作,但我无法捕获数据并制定重写。

标签: wordpressmod-rewriteurl-rewriting

解决方案


以下代码更改guest-authors. 它使用来自 CoAuthor 插件的方法来输出来宾作者链接。

根据插件的意图,至少现在您拥有正确的链接。

它们将采用以下形式:

{site_url}/author/{author_slug}

这是包含在functions.php中的代码:

function adjust_permalink($permalink, $post){
    $post_type = get_post_type($post);
    if($post_type === 'guest-author'){
        global $coauthors_plus;
        $author = $coauthors_plus->get_coauthor_by('ID', $post->ID);
        $permalink = get_author_posts_url( $author->ID, $author->user_nicename );
    }
    return $permalink;
}
add_filter('post_type_link','adjust_permalink',10,2);

现在,您应该能够在主题中为作者创建模板 php 文件:author.php


推荐阅读