<?php namespace hacklabBlocks; /** * Server-side rendering of the `hacklab-blocks/custom-taxonomy` block. * * @package WordPress */ /** * Renders the `hacklab-blocks/custom-taxonomy` block on the server. * * @param array $attributes Block attributes. * @param string $content Block default content. * @param WP_Block $block Block instance. * @return string Returns the filtered post terms for the current post wrapped inside "a" tags. */ add_action('admin_enqueue_scripts', 'hacklabBlocks\\custom_taxonomy_admin_enqueue'); function custom_taxonomy_admin_enqueue() { $args = array( 'public' => true, ); $taxonomies = get_taxonomies($args, 'objects'); $tax_per_pt = []; foreach ($taxonomies as $taxonomy) { $post_types = $taxonomy->object_type; foreach ($post_types as $post_type) { if (!isset($tax_per_pt[$post_type])) { $tax_per_pt[$post_type] = []; } $tax_per_pt[$post_type][] = $taxonomy->name; } } wp_localize_script('hacklab-blocks-custom-taxonomy-editor-script', 'ctaxblock', [ 'taxonomies' => $taxonomies, 'taxPerPt' => $tax_per_pt ]); } function render_block_core_post_terms_2($attributes, $content, $block) { if (!isset($block->context['postId']) || !isset($attributes['selectedTax'])) { return ''; } $post_terms = []; $classes = ''; $taxonomies = $attributes['selectedTax']; foreach ($taxonomies as $taxonomy) { $classes .= 'taxonomy-' . $taxonomy; $tax_terms = []; if (is_taxonomy_viewable($taxonomy)) { $tax_terms = get_the_terms($block->context['postId'], $taxonomy); if (is_array($tax_terms)){ $post_terms = array_merge($post_terms, $tax_terms); } } } $html = ''; if(count($post_terms)){ $separator = empty($attributes['separator']) ? ' ' : $attributes['separator']; $wrapper_attributes = get_block_wrapper_attributes(array('class' => $classes)); $html_array = []; $html .= '<div class="hacklab-custom-taxonomy-block">'; foreach ($post_terms as $term) { // The $term is an object, so we don't need to specify the $taxonomy. $term_link = get_term_link($term); // Make class $class = 'post-term-' . $term->slug . ' post-taxonomy-' . $term->taxonomy; // Check if term has featured color meta $featured_color = get_term_meta( $term->term_id, 'featured_color', true ); if ( $featured_color ) { $class .= ' color-' . sanitize_title( $featured_color ); } // If there was an error, continue to the next term. if (is_wp_error($term_link)) { continue; } // We successfully got a link. Print it out. $html_array[]= '<a class="' . $class . '" href="' . esc_url($term_link) . '">' . $term->name . '</a>'; } $html .= implode($separator, $html_array); $html .= '</div>'; } return $html; }