Close

A First-Rate San Diego SEO Company! 619.754.8846 | 855.475.7046

1 Way to Display Specific Custom Taxonomy for a Custom Post Type

This method filters out what taxonomies you DON’T want to display by searching for that taxonomies slug in the url. If you’ve changed your permalink structure to not include the taxonomy slug, then this won’t work.

// Display specific custom taxonomy items for a custom post type

function gooz_custom_taxonomies_terms_links() {
   // Get post by post ID.
    if ( ! $post = get_post() ) {
        return '';
    }
 
    // Get post type by post.
    $post_type = $post->post_type;
 
    // Get post type taxonomies.
    $taxonomies = get_object_taxonomies( $post_type, 'objects' );
 
    $out = array();
 
    foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
 
        // Get the terms related to post.
        $terms = get_the_terms( $post->ID, $taxonomy_slug );
 
        if ( ! empty( $terms ) ) {
            $out[] = "
<ul>";

            foreach ( $terms as $term ) {

				$term_link = get_term_link( $term );

				// See if the link has the text specific text of taxonomy in it
			    if( strpos($term_link, '/my-custom-taxonomy/') !== false ) {
					$out[] = '';
				} else {
					$out[] = sprintf( '
<li><a href="%1$s">%2$s</a>, </li>

',
						esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
						esc_html( $term->name )
					);
				}
            }
            $out[] = "\n</ul>

\n";
        }
    }
    return implode( '', $out );
}

Then money shot it right here:

 if( strpos($term_link, '/my-custom-taxonomy/') !== false ) {
    $out[] = '';
 } else {
    $out[] = sprintf( '<li><a href="%1$s">%2$s</a>, </li>',
        esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
        esc_html( $term->name )
 );
 }

strpos() is searching the $term_link for the text in the second argument. In this case, it’s ‘/my-custom-taxonomy/’ but you’ll use whatever taxonomy you have. If it finds that text, it won’t display the term associated with that url.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

CLICK HERE to Contact Us Now!