Skip to content

Instantly share code, notes, and snippets.

@chriswagoner
Last active August 11, 2019 03:40
Show Gist options
  • Save chriswagoner/308e30fb680d77f0cce5388633afbb56 to your computer and use it in GitHub Desktop.
Save chriswagoner/308e30fb680d77f0cce5388633afbb56 to your computer and use it in GitHub Desktop.
Add Taxonomy to URL
// Custom Taxonomy Permalinks -- This will use the Taxonomy Variable as part of the URL dynamically
// You will need to add the %variable% from line 10 in your post type like this
// 'rewrite' => array('slug' => '/%variable%', 'with_front' => false)
// or if you're using Toolset then turn on permalink rewrite and add /%variable% as the custom rewrite
add_filter('post_link', 'location_permalink', 10, 3); // Call it what you want
add_filter('post_type_link', 'location_permalink', 10, 3); // Call it what you want
function location_permalink($permalink, $post_id, $leavename) { // Make sure your name matches the filter name above
if (strpos($permalink, '%state%') === FALSE) return $permalink; // The variable you add to your rewrite URL, here we are using %state%
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'state'); // Change 'state' to your tax slug, like 'flower'
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'unknown'; // Change 'unknown' to what you want to output when nothing is selected
return str_replace('%state%', $taxonomy_slug, $permalink); // Change the variable here too
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment