Custom Post Type with modified permalink structure results in 404
-
I’ve defined a custom post type, ‘Review’, that I’d like to utilize with a custom permalink: /reviews/parentcat/childcat/postname. The below code correctly creates the CPT and the custom permalink appears correctly in the administrative panel when creating a new ‘Review’. However, the resulting ‘Review’ that is created returns a 404 when clicking the custom permalink. What is the modern wordpress way of solving this issue? Ideally I’d like not to use any external plugins. The below code is defined within a custom plugin. The permalinks have already been refreshed, that is not the issue.
// Register 'Review' custom post type add_action( 'init', 'vidcreate_post_types' ); // Register the permalink structure desired for 'Review' posts, with placeholders add_action( 'init', 'vidrewrite_rules' ); // Replace permalink placeholders with actual content add_filter('post_type_link', 'update_review_link_placeholders', 10, 2); /** * Custom 'Review' post type */ function vidcreate_post_types() { register_post_type( 'review', array( 'labels' => array( 'name' => __( 'Reviews' ), 'singular_name' => __( 'Review' ) ), 'public' => true, 'has_archive' => true, 'taxonomies' => array('category', 'post_tag'), 'rewrite' => array( 'slug'=>'reviews', 'with_front'=> true, 'feed'=> true, 'pages'=> true ), 'hierarchical' => true, 'menu_icon' => 'dashicons-video-alt', 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions', 'page-attributes' ) ) ); } /** * Create custom permalink structure for 'Review' pages */ function vidrewrite_rules(){ add_rewrite_tag( '%review_slug%', '(reviews)','post_type=review&slug=' ); add_permastruct( 'review', '/reviews/%category%/%review%'); } /** * Update permalinks placeholders with content */ function update_review_link_placeholders($permalink, $post) { if(('review' == $post->post_type) && '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) { // Get category for post $post_categories = wp_get_post_categories( $post->ID ); $cateogryObject = get_category( $post_categories[0] ) ; $category_link = $cateogryObject->slug; // get full category slug, including parent cat if ( $parent = $cateogryObject->parent ) { $category_link = get_category_parents($parent, false, '/', true) . $category_link; } // replace placeholder with slud $permalink = str_replace('%category%', $category_link, $permalink); return $permalink; } }
Viewing 6 replies - 1 through 6 (of 6 total)
Viewing 6 replies - 1 through 6 (of 6 total)
- The topic ‘Custom Post Type with modified permalink structure results in 404’ is closed to new replies.