【问题标题】:How to change the default structure generation of single post permalinks?如何更改单个帖子永久链接的默认结构生成?
【发布时间】:2016-09-27 18:19:02
【问题描述】:

我想更改the_permalink() 函数的输出等。因此,我不想更改所有帖子类型的 mermalink 结构,仅更改“帖子”帖子类型,并且仅更改单个页面。

我已经更改了重写规则,以便

mysite.com/news/2016/the-news-title  

会将用户引导至单个帖子页面模板并正确显示内容。美好的。 现在,正如我所说,我希望 the_permalink() 函数生成具有该结构的链接。

我该怎么做?

【问题讨论】:

    标签: wordpress url-rewriting permalinks


    【解决方案1】:

    我没有找到合适的解决方案,但您可以在此处为帖子类型 post 生成您的永久链接,您有 $post WP_Post Object .. 为什么使用get_post(),因为post_name(永久链接)保存在此字段中,并且始终是唯一的。

    function edit_the_permalink($permalink) {
        $post = get_post(array('post_name' => $permalink));
        if( $post->post_type == 'post' ) {
            // Override your permalink here for post_type = `post`
            echo '<pre>';print_r($post);echo '</pre>';
            $permalink = '';
            return $permalink;
        }
    }
    add_filter('the_permalink', 'edit_the_permalink', 10, 1);
    

    【讨论】:

    • 谢谢,但你确定吗? post_name 用于 slug(实际上,它是 slug):永久链接是多个部分的组合,其中 slug 只是最后一个。
    • 另外,_permalink 过滤器接受 2 个参数,第二个是 post,所以不需要 get_post。请更正您的答案,然后我可以投票;)无论如何,我明白了,这个过滤器适合我的需要,我可以正确构建永久链接。谢谢。
    • @Stratboy 我在这里发布之前测试了我的代码。在我的情况下,第二个参数返回 0 这就是为什么我使用 get_post 作为永久链接。是的,永久链接是更多部分的组合,并且 post_name 始终是唯一的,所以不用担心使用 get_post .. 我很高兴能帮助您找到方法。 :) 谢谢 :)
    • 它返回 0 因为你没有传递 post 对象。请参阅文档:codex.wordpress.org/Function_Reference/the_permalink 和 wp-includes/link-template.php 中的源代码
    【解决方案2】:

    好的,按照 Noman 的指示,我可以发布自己的答案。如果 post_type == 'post',我可以过滤“the_permalink”并修改输出。基本代码:

    add_filter('the_permalink', 'edit_the_permalink', 10, 2);
    function edit_the_permalink($permalink, $post) {
      // you should pass the post object when calling the_permalink()
      if(is_object($post) && $post->post_type == 'post'){
        // [...do the magic...]
        return $permalink;
      }
    }
    

    请注意the_permalink()get_permalink()(别名get_the_permalink())都接受$post 参数,您应该将它作为post 对象传递。

    另外,请注意,如果您想修改自定义帖子类型永久链接生成(get_post_permalink() 的输出),您可以使用 post_type_link 过滤器执行几乎相同的操作。在这种情况下,回调将接收 4 个参数:$post_link、$post、$leavename、$sample。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2013-06-18
      • 1970-01-01
      • 2014-09-22
      相关资源
      最近更新 更多