【问题标题】:Wordpress Custom Permalink Structure for Custom Post Type自定义帖子类型的 Wordpress 自定义永久链接结构
【发布时间】:2016-08-02 14:28:02
【问题描述】:

我花了好几个小时试图找到这个问题的解决方案,阅读了很多文章并尝试了许多来自 stackoverflow 和其他地方的“修复”,但都没有成功。

我正在尝试为我在 Wordpress(版本 4.5.3)中创建的自定义帖子类型创建一个永久链接结构。帖子类型称为“视频”。默认情况下,我的永久链接看起来像“http://localhost.wordpress/videos/my-video-post”。我想用帖子的类别名称替换链接中的“视频”,即 'http://localhost.wordpress/computer-lessons/my-video-post',其中类别是'计算机课程'。我已经能够使用下面的代码创建工作永久链接,例如“http://localhost.wordpress/categories/computer-lessons/my-video-post”,但我想去掉链接中的“/categories/”部分。我目前使用的代码是

add_action( 'init', 'video_post_type' );

function video_post_type() {
    register_post_type( 'video', array(
        'labels' => array(
            'name' => 'Videos',
            'singular_name' => 'Video',
        ),
        'rewrite' => array('slug' => 'categories/%category%'),
        'taxonomies'  => array('post_tag', 'category'),
        'description' => 'Video resources.',
        'public' => true,
        'menu_position' => 20,
        'supports' => array( 'title', 'editor', 'custom-fields' )
      ));
  }

function videos_post_link( $post_link, $id = 0 ){
    $post = get_post($id);  
    if ( is_object( $post ) ){
        $terms = wp_get_object_terms( $post->ID, 'category' );
        if( $terms ){
            return str_replace( '%category%' , $terms[0]->slug ,   $post_link );
        }
    }
    return $post_link;  
}
add_filter( 'post_type_link', 'videos_post_link', 1, 3 );

我已经尝试了很多很多此代码的变体,但每当我得到结构时,我正在寻找永久链接都会给出 404。

我开始认为这可能是不可能的,因为我已经阅读了很多与此相关的文章和帖子,但还没有找到可行的解决方案。

提前非常感谢。

【问题讨论】:

    标签: wordpress custom-post-type permalinks


    【解决方案1】:

    只需将您的部分 'rewrite' => array('slug' => 'categories/%category%') 替换为 'rewrite' => array('slug' => '%category%') 只需离开 %category% 即可。

    重要提示:毕竟转到永久链接选项并重置它。

    您可以在这里找到更多信息Show only specific categories in permalinks for custom post type in WordPress

    【讨论】:

    • 感谢您的回复 mattkrupnik。不幸的是,我无法检查您的解决方案,因为我已经完成了我正在从事的项目并且无法再访问代码,但如果/当我再次遇到此问题时,我一定会尝试您的解决方案。
    猜你喜欢
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 2018-10-21
    相关资源
    最近更新 更多