Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Last active January 21, 2022 02:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielbachhuber/206f2cea8dab1ce73d5a71a04810ac57 to your computer and use it in GitHub Desktop.
Save danielbachhuber/206f2cea8dab1ce73d5a71a04810ac57 to your computer and use it in GitHub Desktop.
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