Last active
July 27, 2021 09:36
-
-
Save bencicpatricija/7c65aa02363ec511248a631035de71cd to your computer and use it in GitHub Desktop.
Woocommerce custom taxonomy term in product base permalink
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
/** | |
* Filter to allow custom non-hierarchical taxonomy terms in the permalinks for products. | |
* | |
* @param string $permalink The existing permalink URL. | |
* @param WP_Post $post WP_Post object. | |
* @return string | |
*/ | |
function pb_custom_product_post_type_link( $permalink, $post ) { | |
// Abort if post is not a product. | |
if ( 'product' !== $post->post_type ) { | |
return $permalink; | |
} | |
// Abort early if the placeholder rewrite tag isn't in the generated URL. | |
if ( false === strpos( $permalink, '%' ) ) { | |
return $permalink; | |
} | |
// Get the custom taxonomy term in use by this post. | |
// Replace "custom_taxonomy_name" with your custom taxonomy slug. | |
$taxonomy_term = get_the_terms( $post->ID, 'custom_taxonomy_name' )[0]; | |
if ( ! empty( $term ) ) { | |
$taxonomy_term_slug = $taxonomy_term->slug; | |
} else { | |
// If no terms are assigned to this post, use a string instead (can't leave the placeholder there). | |
$taxonomy_term_slug = _x( 'uncategorized', 'slug', 'woocommerce' ); | |
} | |
// You can replace "%custom_taxonomy_name%" with anything else you wish to use, this is just the tag name used in Permalinks settings. | |
$permalink = str_replace( '%custom_taxonomy_name%', $taxonomy_term_slug, $permalink ); | |
return $permalink; | |
} | |
add_filter( 'post_type_link', 'pb_custom_product_post_type_link', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment