How about using custom rewrite tags/structure?
So we’ll be using these two rewrite/structure tags:
-
%monthnum2%
does the same thing as the%monthnum%
tag, but without a leading zero; e.g.3
and not03
for March. -
%day2%
does the same thing as the%day%
tag, but without a leading zero; e.g.7
and not07
.
The steps:
-
In the theme functions file (
functions.php
), add:add_action( 'init', function(){ add_rewrite_tag( '%monthnum2%', '([0-9]{1,2})', 'monthnum=' ); add_rewrite_tag( '%day2%', '([0-9]{1,2})', 'day=' ); } );
That will generate the
%monthnum2%
and%day2%
(rewrite) tags and be used when WordPress (re-)generates the rewrite rules.And then add this:
add_filter( 'post_link', function( $permalink, $post ){ if ( preg_match( '/%(?:monthnum2|day2)%/', $permalink ) ) { $time = strtotime( $post->post_date ); $date = explode( ' ', date( 'n j', $time ) ); $permalink = str_replace( [ '%monthnum2%', '%day2%', ], [ $date[0], $date[1], ], $permalink ); $permalink = user_trailingslashit( $permalink, 'single' ); } return $permalink; }, 10, 2 );
That will replace the rewrite tags in the permalink.
-
Go to the permalink settings page and then in the “Custom Structure” box, enter this structure:
/%year%/%monthnum2%/%day2%/%postname%/
or/%author%/%year%/%monthnum2%/%day2%/%postname%
, whichever applies.The point is, use
%monthnum2%
to display the month number without a leading zero and%day2%
to display the day number without a leading zero. -
Save your changes — both the theme functions file and the permalink settings — and go to the “Posts” page (
wp-admin/edit.php
) and just check everything (mouse-over the post permalink and visit the post).