[Cocoon] Display a custom taxonomy if the currently displayed custom post type post has a custom taxonomy.

Genx Beats Avatar

Cocoon uses nesting as a PHP structure, so it won’t work if you just modify single.php. First, copy single.php in the parent theme, place it in the child theme, change the file name to single-custom-post-type-name.php, and edit the following parts of the content. This will separate the behavior for custom post types.

<?php //Post page content
cocoon_template_part('tmp/single-contents-Custom-post-type-name'); ?>

After that, create a folder called tmp in the child theme, duplicate the parent theme’s single-contents.php, place it in the child theme’s tmp folder, name it single-contents-custom-post-type-name.php, edit the following parts of the content. This is also one of the mechanisms to separate the behavior for custom post types.

<?php //Body template
cocoon_template_part('tmp/content-Custom-post-type-name') ?>

After that, copy the parent theme’s content.php, place it in the child theme’s tmp folder, name it content-custom-post-type-name.php, and add the following part anywhere.

<?php //Custom taxonomy categories/tags below the main text
        $post_type = get_post_type();
        $taxonomies = get_object_taxonomies($post_type, 'objects');

        $has_terms = false;

        if (!empty($taxonomies)) {
          foreach ($taxonomies as $taxonomy) {
            $terms = get_the_terms(get_the_ID(), $taxonomy->name);
            if ($terms && !is_wp_error($terms)) {
              $has_terms = true;
              // Show taxonomy name
              echo '<h3>' . esc_html($taxonomy->label) . '</h3>';
              echo '<ul>';
              foreach ($terms as $term) {
                $term_link = get_term_link($term);
                if (!is_wp_error($term_link)) {
                  echo '<li><a href="' . esc_url($term_link) . '">' . esc_html($term->name) . '</a></li>';
                } else {
                  echo '<li>' . esc_html($term->name) . '</li>';
                }
              }
              echo '</ul>';
            }
          }
        }
        ?>

By the way, I decided to put the above code directly below the code below.

<?php //Categories/tags below the main text
        if (is_category_tag_display_position_content_bottom() && is_single()) {
          cocoon_template_part('tmp/categories-tags');
        } ?>

Comments

Leave a Reply