Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Last active October 7, 2020 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cameronjonesweb/a10b7629b9eb0f81b9ff7317ef5be42b to your computer and use it in GitHub Desktop.
Save cameronjonesweb/a10b7629b9eb0f81b9ff7317ef5be42b to your computer and use it in GitHub Desktop.
<?php
add_action( 'init', 'rewrites' );
add_filter( 'post_type_link', 'filter_post_link', 1, 2 );
function rewrites() {
add_rewrite_tag( '%artist%', '([^/]+)' );
add_rewrite_rule(
'songs/([^/]+)/([^/]+)?$',
'index.php?artist=$matches[1]&songs=$matches[2]',
'top'
);
add_rewrite_rule(
'albums/([^/]+)/([^/]+)?$',
'index.php?artist=$matches[1]&albums=$matches[2]',
'top'
);
}
function filter_post_link( $permalink, $post ) {
// Check if the %artist% tag is present in the url:
if ( false === strpos( $permalink, '%artist%' ) ) {
return $permalink;
}
$permalink = replace_artist_rewrite_tag( $permalink, $post );
return $permalink;
}
function rewrite_preview_url( $permalink, $post ) {
if ( in_array( get_post_type( $post->ID ), array( 'albums', 'songs' ) ) ) {
$permalink = add_query_arg( 'artist', '%artist%', $permalink );
$permalink = replace_artist_rewrite_tag( $permalink, $post );
}
return $permalink;
}
function replace_artist_rewrite_tag( $permalink, $post ) {
if ( 'albums' === $post->post_type && get_post_meta( $post->ID, 'compilation', true ) ) {
$artist = 'compilations';
} else {
if( 'songs' === $post->post_type ) {
$artist_id = get_post_meta( $post->ID, 'primary_artist', true );
} else if( 'albums' === $post->post_type ) {
$artist_id = get_post_meta( $post->ID, 'artist', true );
}
$artist_query = new WP_Query( array(
'post_type' => 'artists',
'p' => absint( $artist_id ),
) );
$artist = $artist_query->have_posts() ? $artist_query->posts[0]->post_name : 'unknown-artist';
}
$artist = urlencode( $artist );
// Replace '%artist%'
$permalink = str_replace( '%artist%', $artist , $permalink );
return $permalink;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment