Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
I am creating a custom CPT where I have customized CPT URL structure of CPT, I am using the rewrite rule for this but it is conflicting This is a Lessons CPT, I want to remove lessons from the URL and if any category or subcategory is selected in the post then the URL structure should be parent category/child-category/post name, I have also customized the category URL structure where I want to remove lesson-category in this example:- http://localhost/custom_theme/lesson-category/california/ the URL should be like this http://localhost/custom_theme/california/

I have Custom Lessons CPT where I want to customize the URl structure Here is the scenario:-

I want to remove the lesson in Custom CPT - http://localhost/custom_theme/lesson/paino_lesson/ the URL should be like this http://localhost/custom_theme/paino_lesson/

if any category or subcategory is selected in the post then the URL structure should be parent category/child category/post name,

I want to remove the lesson category in this example:- http://localhost/custom_theme/lesson-category/california/ the URL should be like this http://localhost/custom_theme/california/

// START: CPT 'Lessons'

What I have tried:

// START: CPT 'Lessons'

add_action('init', 'register_lessons_post_type');
function register_lessons_post_type() {
    $labels = array(
        'name'                  => 'Lesson',
        'singular_name'         => 'Lesson',
        'menu_name'             => 'Lesson',
        'add_new'               => 'Add New Lesson',
        'add_new_item'          => 'Add New Lesson',
        'edit_item'             => 'Edit Lesson',
        'new_item'              => 'New Lesson',
        'view_item'             => 'View Lesson',
        'view_items'            => 'View Lessons',
        'search_items'          => 'Search Lessons',
        'not_found'             => 'No lesson found',
        'not_found_in_trash'    => 'No lesson found in trash',
        'all_items'             => 'All Lessons',
        'archives'              => 'Lessons',
        'attributes'            => 'Template',
        'insert_into_item'      => 'Insert into lesson',
        'uploaded_to_this_item' => 'Uploaded to this lesson',
        'filter_items_list'     => 'Filter lessons list',
        'items_list_navigation' => 'Lesson list navigation',
        'items_list'            => 'Lessons list',
        'item_published'        => 'Lesson published',
        'item_published_privately' => 'Lesson published privately',
        'item_reverted_to_draft'    => 'Lesson reverted to draft',
        'item_scheduled'            => 'Lesson scheduled',
        'item_updated'              => 'Lesson updated',
        'taxonomies'               => array( 'lesson_category' ), // Link to the custom taxonomy
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'has_archive'        => true,
        'rewrite'            => array('slug' => '/%lesson_category%'), // Set the custom permalink structure
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-location-alt',
        'supports'           => array('title', 'editor', 'thumbnail','excerpt', 'custom-fields', 'elementor'),
    );

    register_post_type('lessons', $args);
}

add_action('init', 'register_lesson_category_taxonomy');
function register_lesson_category_taxonomy() {
    $labels = array(
        'name' => 'City',
        'singular_name' => 'City',
        'search_items' => 'Search City',
        'all_items' => 'All Cities',
        'parent_item' => 'Parent City or State',
        'parent_item_colon' => 'Parent City or State:',
        'edit_item' => 'Edit City',
        'update_item' => 'Update City',
        'add_new_item' => 'Add New City',
        'new_item_name' => 'New City Name',
        'menu_name' => 'Cities or Locations',
    );

    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array(
            'slug' => '/', // Set the slug for the 'lesson_category' taxonomy
            'with_front' => false,
            'hierarchical' => true
        ),
    );

    // Link this taxonomy to the 'lessons' custom post type
    register_taxonomy('lesson_category', array('lessons'), $args);
}

// Change the permalink structure for the lessons post type
add_filter('post_type_link', 'custom_lessons_permalink_structure', 10, 4);
function custom_lessons_permalink_structure($post_link, $post, $leavename, $sample) {
    if ('lessons' === $post->post_type && 'publish' === $post->post_status) {
        $terms = get_the_terms($post->ID, 'lesson_category');

        if (!empty($terms)) {
            $term_slugs = array();

            foreach ($terms as $term) {
                // Traverse through parent categories and add them to the array
                $parent_chain = get_ancestors($term->term_id, 'lesson_category');
                $parent_chain = array_reverse($parent_chain);
                foreach ($parent_chain as $parent_id) {
                    $parent_term = get_term($parent_id, 'lesson_category');
                    $term_slugs[] = $parent_term->slug;
                }

                $term_slugs[] = $term->slug;
            }

            $post_link = home_url('/') . implode('/', $term_slugs) . '/' . $post->post_name . '/';
        } else {
            // No category selected, keep the URL simple
            $post_link = home_url('/') . $post->post_name . '/';

            
        }
    }

    return $post_link;
}

// Add the %lesson_category% tag to the rewrite rules
add_filter('rewrite_rules_array', 'custom_lessons_rewrite_rules');
function custom_lessons_rewrite_rules($rules) {
    $new_rules = array();

    $terms = get_terms(array('taxonomy' => 'lesson_category', 'hide_empty' => false));

    foreach ($terms as $term) {
        $term_path = $term->slug;
        $new_rules[$term_path . '/([^/]+)/?$'] = 'index.php?lesson_category=$matches[1]';
    }

    // Add a rule for the case when no category is selected
    $new_rules['([^/]+)/?$'] = 'index.php?lessons=$matches[1]';

    return $new_rules + $rules;
}
Posted
Updated 17-Jan-24 5:35am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900