Multiple archives and your permalink structure(/%category%/%postname%/)

CPANathan

Elite Member
Joined
Jul 9, 2019
Messages
2,850
Reaction score
10,253
Edit: It seems to be working, please have a look regardless - you'll likely spot something stupid! <3

I've got an archive for services, I've got an archive for articles, I've got category archives for both.

While setting up my ToC I noticed my permalink structure wasn't set up yet, my articles were all website.com/article, but trying to configure the archive development... Can we add to the list of available tags?

/%archive%/%category%/%postname%/ maybe?

Does anyone know where my overtired brain is going with this? :D

ChatGPT says to go along these lines, but Code Snippets can't get it working and working with Local WP's back-end is not a good idea:

PHP:
// Add custom archive slug handling for permalinks
add_filter('post_link', 'custom_archive_permalink_structure', 10, 3);
add_filter('post_type_link', 'custom_archive_permalink_structure', 10, 3);

function custom_archive_permalink_structure($permalink, $post, $leavename) {
    // Set custom archive slug based on the post type
    if ($post->post_type === 'service') {
        $archive_slug = 'service-archive';
    } elseif ($post->post_type === 'post') {
        $archive_slug = 'article-archive';
    } else {
        return $permalink; // For other post types, use default permalink
    }

    // Replace %archive% with the appropriate archive slug
    if (strpos($permalink, '%archive%') !== false) {
        $permalink = str_replace('%archive%', $archive_slug, $permalink);
    }

    return $permalink;
}

// Register custom rewrite rules to handle new archive-based structure
function custom_archive_rewrite_rules() {
    add_rewrite_tag('%archive%', '([^/]+)');
    add_permastruct('post', '/%archive%/%category%/%postname%/', false);
}

add_action('init', 'custom_archive_rewrite_rules');
 
Last edited:
Back
Top