[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/blocks/ -> navigation-link.php (source)

   1  <?php
   2  /**
   3   * Server-side registering and rendering of the `core/navigation-link` block.
   4   *
   5   * @package WordPress
   6   */
   7  
   8  require_once  __DIR__ . '/navigation-link/shared/item-should-render.php';
   9  require_once  __DIR__ . '/navigation-link/shared/render-submenu-icon.php';
  10  
  11  /**
  12   * Build an array with CSS classes and inline styles defining the colors
  13   * which will be applied to the navigation markup in the front-end.
  14   *
  15   * @since 5.9.0
  16   *
  17   * @param  array $context     Navigation block context.
  18   * @param  array $attributes  Block attributes.
  19   * @param  bool  $is_sub_menu Whether the link is part of a sub-menu. Default false.
  20   * @return array Colors CSS classes and inline styles.
  21   */
  22  function block_core_navigation_link_build_css_colors( $context, $attributes, $is_sub_menu = false ) {
  23      $colors = array(
  24          'css_classes'   => array(),
  25          'inline_styles' => '',
  26      );
  27  
  28      // Text color.
  29      $named_text_color  = null;
  30      $custom_text_color = null;
  31  
  32      if ( $is_sub_menu && array_key_exists( 'customOverlayTextColor', $context ) ) {
  33          $custom_text_color = $context['customOverlayTextColor'];
  34      } elseif ( $is_sub_menu && array_key_exists( 'overlayTextColor', $context ) ) {
  35          $named_text_color = $context['overlayTextColor'];
  36      } elseif ( array_key_exists( 'customTextColor', $context ) ) {
  37          $custom_text_color = $context['customTextColor'];
  38      } elseif ( array_key_exists( 'textColor', $context ) ) {
  39          $named_text_color = $context['textColor'];
  40      } elseif ( isset( $context['style']['color']['text'] ) ) {
  41          $custom_text_color = $context['style']['color']['text'];
  42      }
  43  
  44      // If has text color.
  45      if ( ! is_null( $named_text_color ) ) {
  46          // Add the color class.
  47          array_push( $colors['css_classes'], 'has-text-color', sprintf( 'has-%s-color', $named_text_color ) );
  48      } elseif ( ! is_null( $custom_text_color ) ) {
  49          // Add the custom color inline style.
  50          $colors['css_classes'][]  = 'has-text-color';
  51          $colors['inline_styles'] .= sprintf( 'color: %s;', $custom_text_color );
  52      }
  53  
  54      // Background color.
  55      $named_background_color  = null;
  56      $custom_background_color = null;
  57  
  58      if ( $is_sub_menu && array_key_exists( 'customOverlayBackgroundColor', $context ) ) {
  59          $custom_background_color = $context['customOverlayBackgroundColor'];
  60      } elseif ( $is_sub_menu && array_key_exists( 'overlayBackgroundColor', $context ) ) {
  61          $named_background_color = $context['overlayBackgroundColor'];
  62      } elseif ( array_key_exists( 'customBackgroundColor', $context ) ) {
  63          $custom_background_color = $context['customBackgroundColor'];
  64      } elseif ( array_key_exists( 'backgroundColor', $context ) ) {
  65          $named_background_color = $context['backgroundColor'];
  66      } elseif ( isset( $context['style']['color']['background'] ) ) {
  67          $custom_background_color = $context['style']['color']['background'];
  68      }
  69  
  70      // If has background color.
  71      if ( ! is_null( $named_background_color ) ) {
  72          // Add the background-color class.
  73          array_push( $colors['css_classes'], 'has-background', sprintf( 'has-%s-background-color', $named_background_color ) );
  74      } elseif ( ! is_null( $custom_background_color ) ) {
  75          // Add the custom background-color inline style.
  76          $colors['css_classes'][]  = 'has-background';
  77          $colors['inline_styles'] .= sprintf( 'background-color: %s;', $custom_background_color );
  78      }
  79  
  80      return $colors;
  81  }
  82  
  83  /**
  84   * Decodes a url if it's encoded, returning the same url if not.
  85   *
  86   * @since 6.2.0
  87   *
  88   * @param string $url The url to decode.
  89   *
  90   * @return string $url Returns the decoded url.
  91   */
  92  function block_core_navigation_link_maybe_urldecode( $url ) {
  93      $is_url_encoded = false;
  94      $query          = parse_url( $url, PHP_URL_QUERY );
  95      $query_params   = wp_parse_args( $query );
  96  
  97      foreach ( $query_params as $query_param ) {
  98          $can_query_param_be_encoded = is_string( $query_param ) && ! empty( $query_param );
  99          if ( ! $can_query_param_be_encoded ) {
 100              continue;
 101          }
 102          if ( rawurldecode( $query_param ) !== $query_param ) {
 103              $is_url_encoded = true;
 104              break;
 105          }
 106      }
 107  
 108      if ( $is_url_encoded ) {
 109          return rawurldecode( $url );
 110      }
 111  
 112      return $url;
 113  }
 114  
 115  
 116  /**
 117   * Renders the `core/navigation-link` block.
 118   *
 119   * @since 5.9.0
 120   *
 121   * @param array    $attributes The block attributes.
 122   * @param string   $content    The saved content.
 123   * @param WP_Block $block      The parsed block.
 124   *
 125   * @return string Returns the post content with the legacy widget added.
 126   */
 127  function render_block_core_navigation_link( $attributes, $content, $block ) {
 128      // Check if this navigation item should render based on post status.
 129      if ( defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN ) {
 130          $should_render = gutenberg_block_core_shared_navigation_item_should_render( $attributes, $block );
 131      } else {
 132          $should_render = block_core_shared_navigation_item_should_render( $attributes, $block );
 133      }
 134      if ( ! $should_render ) {
 135          return '';
 136      }
 137  
 138      // Don't render the block's subtree if it has no label.
 139      if ( empty( $attributes['label'] ) ) {
 140          return '';
 141      }
 142  
 143      $classes = array();
 144  
 145      // Render inner blocks first to check if any menu items will actually display.
 146      $inner_blocks_html = '';
 147      foreach ( $block->inner_blocks as $inner_block ) {
 148          $inner_blocks_html .= $inner_block->render();
 149      }
 150      $has_submenu = ! empty( trim( $inner_blocks_html ) );
 151  
 152      $css_classes = trim( implode( ' ', $classes ) );
 153      $kind        = empty( $attributes['kind'] ) ? 'post_type' : str_replace( '-', '_', $attributes['kind'] );
 154      $is_active   = ! empty( $attributes['id'] ) && get_queried_object_id() === (int) $attributes['id'] && ! empty( get_queried_object()->$kind );
 155  
 156      if ( is_post_type_archive() && ! empty( $attributes['url'] ) ) {
 157          $queried_archive_link = get_post_type_archive_link( get_queried_object()->name );
 158          if ( $attributes['url'] === $queried_archive_link ) {
 159              $is_active = true;
 160          }
 161      }
 162  
 163      $wrapper_attributes = get_block_wrapper_attributes(
 164          array(
 165              'class' => $css_classes . ' wp-block-navigation-item' . ( $has_submenu ? ' has-child' : '' ) .
 166                  ( $is_active ? ' current-menu-item' : '' ),
 167          )
 168      );
 169      $html               = '<li ' . $wrapper_attributes . '>' .
 170          '<a class="wp-block-navigation-item__content" ';
 171  
 172      // Start appending HTML attributes to anchor tag.
 173      if ( isset( $attributes['url'] ) ) {
 174          $html .= ' href="' . esc_url( block_core_navigation_link_maybe_urldecode( $attributes['url'] ) ) . '"';
 175      }
 176  
 177      if ( $is_active ) {
 178          $html .= ' aria-current="page"';
 179      }
 180  
 181      if ( isset( $attributes['opensInNewTab'] ) && true === $attributes['opensInNewTab'] ) {
 182          $html .= ' target="_blank"  ';
 183      }
 184  
 185      if ( isset( $attributes['rel'] ) ) {
 186          $html .= ' rel="' . esc_attr( $attributes['rel'] ) . '"';
 187      } elseif ( isset( $attributes['nofollow'] ) && $attributes['nofollow'] ) {
 188          $html .= ' rel="nofollow"';
 189      }
 190  
 191      if ( isset( $attributes['title'] ) ) {
 192          $html .= ' title="' . esc_attr( $attributes['title'] ) . '"';
 193      }
 194  
 195      // End appending HTML attributes to anchor tag.
 196  
 197      // Start anchor tag content.
 198      $html .= '>' .
 199          // Wrap title with span to isolate it from submenu icon.
 200          '<span class="wp-block-navigation-item__label">';
 201  
 202      if ( isset( $attributes['label'] ) ) {
 203          $html .= wp_kses_post( $attributes['label'] );
 204      }
 205  
 206      $html .= '</span>';
 207  
 208      // Add description if available.
 209      if ( ! empty( $attributes['description'] ) ) {
 210          $html .= '<span class="wp-block-navigation-item__description">';
 211          $html .= wp_kses_post( $attributes['description'] );
 212          $html .= '</span>';
 213      }
 214  
 215      $html .= '</a>';
 216      // End anchor tag content.
 217  
 218      if ( isset( $block->context['showSubmenuIcon'] ) && $block->context['showSubmenuIcon'] && $has_submenu ) {
 219          // The submenu icon can be hidden by a CSS rule on the Navigation Block.
 220          $html .= '<span class="wp-block-navigation__submenu-icon">';
 221          if ( defined( 'IS_GUTENBERG_PLUGIN' ) && IS_GUTENBERG_PLUGIN ) {
 222              $html .= gutenberg_block_core_shared_navigation_render_submenu_icon();
 223          } else {
 224              $html .= block_core_shared_navigation_render_submenu_icon();
 225          }
 226          $html .= '</span>';
 227      }
 228  
 229      if ( $has_submenu ) {
 230          $html .= sprintf(
 231              '<ul class="wp-block-navigation__submenu-container">%s</ul>',
 232              $inner_blocks_html
 233          );
 234      }
 235  
 236      $html .= '</li>';
 237  
 238      return $html;
 239  }
 240  
 241  /**
 242   * Returns a navigation link variation
 243   *
 244   * @since 5.9.0
 245   *
 246   * @param WP_Taxonomy|WP_Post_Type $entity post type or taxonomy entity.
 247   * @param string                   $kind string of value 'taxonomy' or 'post-type'.
 248   *
 249   * @return array
 250   */
 251  function build_variation_for_navigation_link( $entity, $kind ) {
 252      $title       = '';
 253      $description = '';
 254  
 255      // Get default labels based on entity type
 256      $default_labels = null;
 257      if ( $entity instanceof WP_Post_Type ) {
 258          $default_labels = WP_Post_Type::get_default_labels();
 259      } elseif ( $entity instanceof WP_Taxonomy ) {
 260          $default_labels = WP_Taxonomy::get_default_labels();
 261      }
 262  
 263      // Get title and check if it's default
 264      $is_default_title = false;
 265      if ( property_exists( $entity->labels, 'item_link' ) ) {
 266          $title = $entity->labels->item_link;
 267          if ( isset( $default_labels['item_link'] ) ) {
 268              $is_default_title = in_array( $title, $default_labels['item_link'], true );
 269          }
 270      }
 271  
 272      // Get description and check if it's default
 273      $is_default_description = false;
 274      if ( property_exists( $entity->labels, 'item_link_description' ) ) {
 275          $description = $entity->labels->item_link_description;
 276          if ( isset( $default_labels['item_link_description'] ) ) {
 277              $is_default_description = in_array( $description, $default_labels['item_link_description'], true );
 278          }
 279      }
 280  
 281      // Calculate singular name once (used for both title and description)
 282      $singular = $entity->labels->singular_name ?? ucfirst( $entity->name );
 283  
 284      // Set default title if needed
 285      if ( $is_default_title || '' === $title ) {
 286          /* translators: %s: Singular label of the entity. */
 287          $title = sprintf( __( '%s link' ), $singular );
 288      }
 289  
 290      // Default description if needed.
 291      // Use a single space character instead of an empty string to prevent fallback to the
 292      // block.json default description ("Add a page, link, or another item to your navigation.").
 293      // An empty string would be treated as missing and trigger the fallback, while a single
 294      // space appears blank in the UI but prevents the fallback behavior.
 295      // We avoid generating descriptions like "A link to a %s" to prevent grammatical errors
 296      // (e.g., "A link to a event" should be "A link to an event").
 297      if ( $is_default_description || '' === $description ) {
 298          $description = ' ';
 299      }
 300  
 301      $variation = array(
 302          'name'        => $entity->name,
 303          'title'       => $title,
 304          'description' => $description,
 305          'attributes'  => array(
 306              'type' => $entity->name,
 307              'kind' => $kind,
 308          ),
 309      );
 310  
 311      // Tweak some value for the variations.
 312      $variation_overrides = array(
 313          'post_tag'    => array(
 314              'name'       => 'tag',
 315              'attributes' => array(
 316                  'type' => 'tag',
 317                  'kind' => $kind,
 318              ),
 319          ),
 320          'post_format' => array(
 321              // The item_link and item_link_description for post formats is the
 322              // same as for tags, so need to be overridden.
 323              'title'       => __( 'Post Format Link' ),
 324              'description' => __( 'A link to a post format' ),
 325              'attributes'  => array(
 326                  'type' => 'post_format',
 327                  'kind' => $kind,
 328              ),
 329          ),
 330      );
 331  
 332      if ( array_key_exists( $entity->name, $variation_overrides ) ) {
 333          $variation = array_merge(
 334              $variation,
 335              $variation_overrides[ $entity->name ]
 336          );
 337      }
 338  
 339      return $variation;
 340  }
 341  
 342  /**
 343   * Filters the registered variations for a block type.
 344   * Returns the dynamically built variations for all post-types and taxonomies.
 345   *
 346   * @since 6.5.0
 347   *
 348   * @param array         $variations Array of registered variations for a block type.
 349   * @param WP_Block_Type $block_type The full block type object.
 350   * @return array Numerically indexed array of block variations.
 351   */
 352  function block_core_navigation_link_filter_variations( $variations, $block_type ) {
 353      if ( 'core/navigation-link' !== $block_type->name ) {
 354          return $variations;
 355      }
 356  
 357      $generated_variations = block_core_navigation_link_build_variations();
 358  
 359      /*
 360       * IMPORTANT: Order matters for deduplication.
 361       *
 362       * The variations returned from this filter are bootstrapped to JavaScript and
 363       * processed by the block variations reducer. The reducer uses `getUniqueItemsByName()`
 364       * (packages/blocks/src/store/reducer.js:51-57) which keeps the FIRST variation with
 365       * a given 'name' and discards later duplicates when processing the array in order.
 366       *
 367       * By placing generated variations first in `array_merge()`, the improved
 368       * labels (e.g., "Product link" instead of generic "Post Link") are processed first
 369       * and preserved. The generic incoming variations are then discarded as duplicates.
 370       *
 371       * Why `array_merge()` instead of manual deduplication?
 372       * - Both arrays use numeric indices (0, 1, 2...), so `array_merge()` concatenates
 373       *   and re-indexes them sequentially, preserving order
 374       * - The reducer handles deduplication, so it is not needed here
 375       * - This keeps the PHP code simple and relies on the established JavaScript behavior
 376       *
 377       * See: https://github.com/WordPress/gutenberg/pull/72517
 378       */
 379      return array_merge( $generated_variations, $variations );
 380  }
 381  
 382  /**
 383   * Returns an array of variations for the navigation link block.
 384   *
 385   * @since 6.5.0
 386   *
 387   * @return array
 388   */
 389  function block_core_navigation_link_build_variations() {
 390      $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
 391      $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
 392  
 393      /*
 394       * Use two separate arrays as a way to order the variations in the UI.
 395       * Known variations (like Post Link and Page Link) are added to the
 396       * `built_ins` array. Variations for custom post types and taxonomies are
 397       * added to the `variations` array and will always appear after `built-ins.
 398       */
 399      $built_ins  = array();
 400      $variations = array();
 401  
 402      if ( $post_types ) {
 403          foreach ( $post_types as $post_type ) {
 404              $variation = build_variation_for_navigation_link( $post_type, 'post-type' );
 405              if ( $post_type->_builtin ) {
 406                  $built_ins[] = $variation;
 407              } else {
 408                  $variations[] = $variation;
 409              }
 410          }
 411      }
 412      if ( $taxonomies ) {
 413          foreach ( $taxonomies as $taxonomy ) {
 414              $variation = build_variation_for_navigation_link( $taxonomy, 'taxonomy' );
 415              if ( $taxonomy->_builtin ) {
 416                  $built_ins[] = $variation;
 417              } else {
 418                  $variations[] = $variation;
 419              }
 420          }
 421      }
 422  
 423      $all_variations = array_merge( $built_ins, $variations );
 424  
 425      return $all_variations;
 426  }
 427  
 428  /**
 429   * Registers the navigation link block.
 430   *
 431   * @since 5.9.0
 432   *
 433   * @uses render_block_core_navigation_link()
 434   * @throws WP_Error An WP_Error exception parsing the block definition.
 435   */
 436  function register_block_core_navigation_link() {
 437      register_block_type_from_metadata(
 438          __DIR__ . '/navigation-link',
 439          array(
 440              'render_callback' => 'render_block_core_navigation_link',
 441          )
 442      );
 443  }
 444  add_action( 'init', 'register_block_core_navigation_link' );
 445  /**
 446   * Creates all variations for post types / taxonomies dynamically (= each time when variations are requested).
 447   * Do not use variation_callback, to also account for unregistering post types/taxonomies later on.
 448   */
 449  add_filter( 'get_block_type_variations', 'block_core_navigation_link_filter_variations', 10, 2 );


Generated : Mon Jul 20 08:20:16 2026 Cross-referenced by PHPXref