Skip to content

Instantly share code, notes, and snippets.

@Garconis
Created June 29, 2018 16:58
Show Gist options
  • Save Garconis/d4995f5cd4515883629aeb0e95482e5b to your computer and use it in GitHub Desktop.
Save Garconis/d4995f5cd4515883629aeb0e95482e5b to your computer and use it in GitHub Desktop.
WordPress | Forcing rewrite of CPT post based on the selected taxonomy term
<?php
/**
* Define default terms for custom taxonomies in WordPress 3.0.1
*
* @author Michael Fields http://wordpress.mfields.org/
* @props John P. Bloch http://www.johnpbloch.com/
* @props Evan Mulins https://circlecube.com/circlecube/
*
* @since 2010-09-13
* @alter 2013-01-31
*
* @license GPLv2
*/
// force the "General" category taxonomy term to be added if nothing is selected for the Focus Post category
// this is useful because we are forcing the fs_focus_post_category (Taxonomy Term) to populate as part of the permalink
// and if there was a post without a category, then that variable in the permalink would not look good
function mfields_set_default_object_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status && $post->post_type === 'fs_focus_posts' ) {
$defaults = array(
'fs_focus_post_category' => array( 'general' )
);
$taxonomies = get_object_taxonomies( $post->post_type );
foreach ( (array) $taxonomies as $taxonomy ) {
$terms = wp_get_post_terms( $post_id, $taxonomy );
if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
}
}
}
}
add_action( 'save_post', 'mfields_set_default_object_terms', 100, 2 );
// force rewrite the permalink of the Focus Post CPT post, since we are injecting the fs_focus_post_category (Taxonomy) into the slug rewrite via CPT UI
function wpa_show_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'fs_focus_posts' ){
$terms = wp_get_object_terms( $post->ID, 'fs_focus_post_category' );
if( $terms ){
return str_replace( '%fs_focus_post_category%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );
// this is an alternate method to fix the Focus Post slug with the taxonomy in case the one above doesnt work well
/*
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'fs_focus_posts')
return $link;
if ($cats = get_the_terms($post->ID, 'fs_focus_post_category'))
$link = str_replace('%fs_focus_post_category%', array_pop($cats)->slug, $link);
return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);
*/
@Garconis
Copy link
Author

FS Focus Posts created via CPT UI: https://d.pr/free/i/kslng0
FS Focus Posts Categories via CPT UI: https://d.pr/free/i/63JLfU

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