Created
January 3, 2023 06:08
-
-
Save brandonjp/90cb1964220f97254e52d4504818f6f2 to your computer and use it in GitHub Desktop.
Wordpress URLs: Add custom taxonomy to permalink structure - Allows you to use the /%name%/ of a custom taxonomy in permalink structures. Be sure to set $taxName and $default variables. Adapted from: https://www.shibashake.com/wp/add-custom-taxonomy-tags-to-your-wordpress-permalinks - Code Snippets Pro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Adapted from: https://www.shibashake.com/wp/add-custom-taxonomy-tags-to-your-wordpress-permalinks | |
namespace Bs3LfBs; | |
function add_custom_tax_permalink($permalink, $post_id, $leavename) { | |
// name of the custom taxonomy | |
$taxName = 'song'; | |
// fallback term to use if a post does not have any attached terms | |
$default = 'misc'; | |
if (strpos($permalink, "%$taxName%") === FALSE) return $permalink; | |
// Get post | |
$post = get_post($post_id); | |
if (!$post) return $permalink; | |
// Get taxonomy terms | |
$terms = wp_get_object_terms($post->ID, $taxName); | |
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug; | |
else $taxonomy_slug = $default; | |
return str_replace("%$taxName%", $taxonomy_slug, $permalink); | |
} | |
add_filter('post_link', '\Bs3LfBs\add_custom_tax_permalink', 10, 3); | |
add_filter('post_type_link', '\Bs3LfBs\add_custom_tax_permalink', 10, 3); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For Code Snippets Pro - https://codesnippets.pro/
Allows you to use the /%name%/ of a custom taxonomy in permalink structures. Be sure to set $taxName and $default variables.
Adapted from: https://www.shibashake.com/wp/add-custom-taxonomy-tags-to-your-wordpress-permalinks