Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Need to replace CPT slug by taxonomy's WordPress

  • REFUNDED

My current code already does that, but it breaks the rest of the site's permalinks.
I tracked down the error to the heart of the trick - using %listing_type% as the slug for the CPT to later replace it with the taxonomy's.

There seems to be some rewrites missing to complete my code below (I'm not using plugins)

The provided code must use the wp hooks an filters (latest ones) so WP is aware about anything is happening, and nothing I do later would break it, e.g. no .htaccess rewrites. To do it sloppy i can do it myself, as you can see, hehe.

I'll edit it later to ensure which terms should be used for the CPTs permalink.



/* ************** Listing Types *************** */

function register_taxonomy_listing_type() {
…etc
$args = array(
…etc
'rewrite' => array('slug' => 'listing_type', 'with_front' => false, 'hierarchical' => false),
'query_var' => true
);

register_taxonomy( 'listing_type', array('listing'), $args );
}

add_action( 'init', 'register_taxonomy_listing_type' );


/* ******************* Listings ****************** */


function register_cpt_listing() {

…etc

$args = array(
…etc
'hierarchical' => true,
'taxonomies' => array( 'attractions', 'tours', 'events' ),
'rewrite' => array(
'slug' => '/%listing_type%',
'with_front' => false,
'feeds' => true,
'pages' => false
),
'capability_type' => 'post'
);

register_post_type( 'listing', $args );

add_action( 'init', 'register_cpt_listing' );

// ------------… rewrites for listings needed here
}


function listing_type_link_filter_function( $post_link, $id = 0 ) {
if ( strpos('%listing_type%', $post_link) === 'FALSE' ) {
return $post_link;
}
$post = get_post($id);
if ( !is_object($post) || $post->post_type != 'listing' ) {
return $post_link;
}
$terms = wp_get_object_terms($post->ID, 'listing_type');
if ( !$terms ) {
return str_replace('/listing_type', '/', $post_link);
}
return str_replace('%listing_type%', $terms[0]->slug, $post_link);
}

add_filter('post_type_link', 'listing_type_link_filter_function', 1, 9);


function term_link_filter_function( $termlink, $term ) {
if ( strpos('listing_type', $termlink) === 'FALSE' ) {
return $termlink;
} else return str_replace('/listing_type', '', $termlink);
}

add_filter('term_link', 'term_link_filter_function', 1, 2);



You can see it working at http://flakeyfish.com/recommended
(the big tabs are the CPT's taxonomy listing_type)

Answers (1)

2012-07-25

Arnav Joy answers:

try using this

flush_rewrite_rules( );

see this

http://codex.wordpress.org/Function_Reference/flush_rewrite_rules


socialblogsite comments:

Really?
Have you read the description?

If I hadn't fushed the rules the original pretty permalinks would still be working and nothing I did would.