duanjuan1103 2019-04-14 01:13
浏览 101

当我重写我的自定义帖子类型的slug时,为什么我的页面404?

I'm working with a wordpress theme I purchased for a glassblowing business and it provides me with a custom post type called "portfolio".

What I'm trying to do is rewrite the slug of that custom post type to match the type of product it is.

If the product were under the "lighting" category, the URL would be domain.com/lighting/product-name

If the product were under the "object" category, the URL would be domain.com/objects/product-name

I can get the desired permalink structure for my posts by adding the following code to my child theme's functions.php, but when I do, all of my other pages (minus the home page) return a 404.

add_filter( 'register_post_type_args', 'dynamic_keep_product_slug', 10, 2 );
function dynamic_keep_product_slug( $args, $post_type ) {

    if ( 'portfolio' === $post_type ) {
        $my_args = array(
            'rewrite' => array( 'slug' => '%project-type%', 'with_front' => true ),
            'hierarchical' => true,
            'taxonomies' => array('category')
        );
        return array_merge( $args, $my_args );
    }

    return $args;
}

function keep_product_link( $post_link, $id = 0 ) {
    $post = get_post($id);
    $terms = wp_get_object_terms( $post->ID, 'project-type' );
    if( $terms ){
        return str_replace( '%project-type%' , $terms[0]->slug , $post_link );
    } else {
        return str_replace( '%project-type%' , 'products' , $post_link );
    }

    return $post_link;
}

add_filter( 'post_type_link', 'keep_product_link', 10, 2 );

I'm far from an expert, so can someone tell me where I've gone wrong here? Is there a better way of giving this post type multiple slug options?

  • 写回答

1条回答 默认 最新

  • doutao4480 2019-04-15 09:36
    关注

    You might have to (re)save permalinks. After changing stuff like taxonomy and slugs, you get 404 if you don't. Go to the WP dashboard and head to Settings > Permalinks and just hit save.

    Also, you can consider another way to do this. Leave the CPT unchanged and create categories for it, lighting, objects, etc. Then remove the CPT slug from the url. It will kepp the CPT category slug and that's what you want. Just note that in this case you can't have any pages or posts whose slugs start with "portfolio", or conflicts would arise. Apart from that it works fine, I've done this with woocommerce, hiding the "product" slug but keeping the categories' slugs

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染