Created
May 23, 2021 21:14
-
-
Save frankyonnetti/80ed0918b0ac36a932143e9c549f9445 to your computer and use it in GitHub Desktop.
WordPress - use taxonomy in permalink URL #wordpress #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
<?php | |
// https://wordpress.org/support/topic/how-to-add-custom-taxonomy-in-custom-post-type-permalink | |
// Create Asset Custom Post Type | |
function create_the_asset_posttype() { | |
$labels = array( | |
... | |
'name' => __( 'Asset' ), | |
); | |
$args = array( | |
... | |
'taxonomies' => array( 'campaign' ), | |
'show_admin_column' => true, | |
'rewrite' => array('slug' => 'asset/%campaign%'), | |
); | |
register_post_type( 'asset', $args ); | |
} | |
add_action( 'init', 'create_the_asset_posttype', 0 ); | |
// Custom Post Type Texonomies | |
function create_the_asset_taxonomy() { | |
register_taxonomy( | |
'campaign', //The name of the taxonomy. | |
'asset', //post type name | |
array( | |
'hierarchical' =>'asset', // name of CPT | |
'label' => 'Campaigns', //Display name | |
'query_var' => true, | |
'has_archive' => true, | |
'rewrite' => array('slug' => 'asset') | |
) | |
); | |
} | |
add_action( 'init', 'create_the_asset_taxonomy' ); | |
// functions.php | |
function wpa_course_post_link( $post_link, $id = 0 ) { | |
$post = get_post($id); | |
if ( is_object( $post ) ) { | |
$terms = wp_get_object_terms( $post->ID, 'campaign' ); | |
if ( $terms ) { | |
return str_replace( '%campaign%' , $terms[0]->slug , $post_link ); | |
} | |
} | |
return $post_link; | |
} | |
add_filter( 'post_type_link', 'wpa_course_post_link', 1, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment