Skip to content

Instantly share code, notes, and snippets.

@paulgrieselhuber
Created November 22, 2022 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulgrieselhuber/765bf9022e05a91ddd733684cdc77cce to your computer and use it in GitHub Desktop.
Save paulgrieselhuber/765bf9022e05a91ddd733684cdc77cce to your computer and use it in GitHub Desktop.
Adding logic to tell Wordpress to prepend `/articles/` to Posts only
function add_rewrite_rules($wp_rewrite) {
$new_rules = array(
'articles/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');
function change_blog_links($post_link, $id=0) {
$post = get_post($id);
if(is_object($post) && $post->post_type == 'post'){
if ($post->post_status == "publish") {
return home_url('/articles/'. $post->post_name.'/');
}
if (is_admin()) {
return home_url('/?p='. $post->ID . '&preview=true');
}
}
return $post_link;
}
add_filter('post_link', 'change_blog_links', 1, 3);
// ht Fury on Stack Overflow for the original version of this
// see: https://wordpress.stackexchange.com/questions/52471/permalinks-question-adding-a-prefix-only-in-front-of-the-posts/63895#63895
@paulgrieselhuber
Copy link
Author

View the related post for this code snippet, which discussed safely changing URL structure at the LoudNoises blog: https://www.loudnoises.us/blog/the-toe-dip-method-for-changing-url-structure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment