Skip to content

Instantly share code, notes, and snippets.

@mattwatsoncodes
Last active July 4, 2023 11:59
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 mattwatsoncodes/af39886baee89e51e296 to your computer and use it in GitHub Desktop.
Save mattwatsoncodes/af39886baee89e51e296 to your computer and use it in GitHub Desktop.
Code to change the WordPress re-write slugs based on the Author and Faculty parameters
<?php
// Add the following re-write rule to the CPT, out of context here so commented out
//'rewrite' => array( 'slug' => __( '%faculty%/%author%/journal', 'aspire' ) ),
function aspire_register_rewrite_tags() {
// add our rewrite tags
// query at the end allows a custom param, however having it at the start of our URL with no prefix does cause issues
add_rewrite_tag( '%faculty%', '([^&]+)' /*, 'author='*/ );
}
add_action( 'init', 'aspire_register_rewrite_tags');
// This does the URL rewrite based on the rewrite tags
function aspire_post_type_link( $post_link, $post, $leavename, $sample ) {
// Check that we are on a Journal page (however we probably want to check a few of these)
if ( 'journal' != get_post_type( $post ) )
return $post_link;
$authordata = get_userdata( $post->post_author );
$author = $authordata->user_nicename;
// Replace the Author
$post_link = str_replace( '%author%', $author, $post_link );
// Replace the faculty (we can use custom meta, but this is good for a test)
$post_link = str_replace( '%faculty%', 'my-test-faculty', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'aspire_post_type_link', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment