Skip to content

Instantly share code, notes, and snippets.

@strangerstudios
Created February 20, 2015 13:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save strangerstudios/ca9d65998270ef89c242 to your computer and use it in GitHub Desktop.
Save strangerstudios/ca9d65998270ef89c242 to your computer and use it in GitHub Desktop.
Use template_redirect and post_type_link filters in WordPress to remove the CPT slug from the front of CPT URLs.
/*
If 404 on a post, look for a gallery or portfolio with the same slug.
Borrows from: https://wordpress.stackexchange.com/a/45081/3652
*/
function my_cpt_404_redirects($template)
{
if(is_404())
{
//see if we know the exact post ID
$id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id'));
$redirect_url = false;
if ($id && $redirect_post = get_post($id)) {
$post_type_obj = get_post_type_object($redirect_post->post_type);
if ($post_type_obj->public)
$redirect_url = get_permalink($redirect_post);
}
//if not, let's see if there is a gallery or portfolio with the same slug and date
if (!$redirect_url)
{
global $wp_query, $post, $post_type, $wpdb;
$sqlQuery = "SELECT ID FROM $wpdb->posts WHERE post_type IN('galleries', 'portfolios') AND post_status = 'publish' AND YEAR(post_date) = '" . esc_sql($wp_query->query_vars['year']) . "' AND MONTH(post_date) = '" . esc_sql($wp_query->query_vars['monthnum']) . "' AND post_name = '" . esc_sql($wp_query->query_vars['name']) . "' LIMIT 1";
$post_id = $wpdb->get_var($sqlQuery);
if(!empty($post_id))
{
//found one!
//reset the query
$wp_query = new WP_Query('p=' . $post_id);
//reset global $post
$post = get_post($post_id);
$post_type = $post->post_type;
setup_postdata( $post->ID);
//don't redirect to the canonical URL
remove_filter('template_redirect', 'redirect_canonical');
//reset 404 to 200 status
status_header(200);
}
}
}
else
{
/*
//debug
global $wp_query;
d($wp_query);
*/
}
return $template;
}
add_action('template_redirect', 'my_cpt_404_redirects', 5);
/*
Change permalinks for portfolios and galleries to use year/month/slug
*/
function my_post_link($url, $post, $leavename)
{
$status = $post->post_status;
$type = $post->post_type;
if($status == "publish" && ($type == "galleries" || $type == "portfolios"))
{
$unixtime = strtotime($post->post_date);
$date = explode(" ",date('Y m d H i s', $unixtime));
$url = home_url($date[0] . "/" . $date[1] . "/" . $post->post_name . "/");
}
return $url;
}
add_filter('post_type_link', 'my_post_link', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment