Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating a blog post archive at /blog/ without awkwardly publishing a page
<?php
add_filter( 'register_post_type_args', function( $args, $post_type ) {
global $wp_rewrite;
if ( 'post' === $post_type && ! is_null( $wp_rewrite ) ) {
$archive_slug = 'blog';
// Setting 'has_archive' ensures get_post_type_archive_template() returns an archive.php template.
$args['has_archive'] = $archive_slug;
// We have to register rewrite rules, because WordPress won't do it for us unless $args['rewrite'] is true.
$archive_slug = $wp_rewrite->root . $archive_slug;
add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
$feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
}
return $args;
}, 10, 2 );
add_filter( 'post_type_archive_link', function( $link, $post_type ) {
if ( 'post' === $post_type ) {
$link = home_url( 'blog/' );
}
return $link;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.