I created a custom post type, of which the (simplified) arguments are:
register_post_type(
'Event',
'public' => true,
'rewrite' => array( 'slug' => 'eventy'),
'has_archive' => false,
'hierarchical' => false
)
It works fine in general. However if I try to rewrite the URLs in functions.php
, for example:
function my_post_type_link_filter_function( $post_link, $id = 0, $leavename = FALSE ) {
return str_replace('eventy', 'eventx', $post_link);
}
add_filter('post_type_link', 'my_post_type_link_filter_function', 1, 3);
The result is that the new ‘eventx’ URLs appear correctly in links, lists, etc, generated
by WordPress. But when I go to those ‘eventx’ URLs I get a 404. Going to an ‘eventy’ URL still works.
I’ve tried changing the permalinks settings to default and back to post name, many times. This is supposed to reset permalinks and fixes this issue for many people I’ve seen online. Not for me.
Anyone know what the cause might be? How do I go about troubleshooting this? I’m weak on the theory of URL rewriting.
If you’re interested, my purpose is not the trivial eventy → eventx substitution mentioned above. I actually want to slip in the year/month an event starts (not when it was was published) into its URL. Debugging got me to realise I had a more basic issue as even this trivial x → y rewrite still throws 404s.
Thanks for reading!
[clarification added]
At the moment I have say three events (posts in my custom post type) called say “Fishing trip”. These get assigned permalinks by default like
- mysite.com/events/fishing-trip
- mysite.com/events/fishing-trip-2
- mysite.com/events/fishing-trip-3
Which is boring and inelegant.
I want instead
- mysite.com/events/2013/january/fishing-trip
- mysite.com/events/2013/may/fishing-trip
- mysite.com/events/2013/may/fishing-trip-2
- mysite.com/events/2014/march/fishing-trip
Prettier and more informative.
I’m not interested in having category-style pages like
- mysite.com/events/2013
The year and month is just cosmetic in the URL.
Step 1, add the rewrite tags for custom event year and month query vars, then register the event post type with those tags in the slug argument of the rewrite argument:
Step 2, filter the post type link to replace those tags with values from custom fields
event_year
andevent_month
. If the custom fields don’t exist, some default values are inserted so you can at least preview a post without error:You have to set ‘rewrite’ => false in your register_post_type(); and add after closing register_post_type() :
Where projet is my CPT.
You can check here for more.