[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/blocks/ -> latest-posts.php (source)

   1  <?php
   2  /**
   3   * Server-side rendering of the `core/latest-posts` block.
   4   *
   5   * @package WordPress
   6   */
   7  
   8  /**
   9   * The excerpt length set by the Latest Posts core block
  10   * set at render time and used by the block itself.
  11   *
  12   * @var int
  13   */
  14  global $block_core_latest_posts_excerpt_length;
  15  $block_core_latest_posts_excerpt_length = 0;
  16  
  17  /**
  18   * Callback for the excerpt_length filter used by
  19   * the Latest Posts block at render time.
  20   *
  21   * @since 5.4.0
  22   *
  23   * @global int $block_core_latest_posts_excerpt_length Excerpt length set by the Latest Posts core block.
  24   *
  25   * @return int Returns the global $block_core_latest_posts_excerpt_length variable
  26   *             to allow the excerpt_length filter respect the Latest Block setting.
  27   */
  28  function block_core_latest_posts_get_excerpt_length() {
  29      global $block_core_latest_posts_excerpt_length;
  30      return $block_core_latest_posts_excerpt_length;
  31  }
  32  
  33  /**
  34   * Renders the `core/latest-posts` block on server.
  35   *
  36   * @since 5.0.0
  37   *
  38   * @global WP_Post $post                                   Global post object.
  39   * @global int     $block_core_latest_posts_excerpt_length Excerpt length set by the Latest Posts core block.
  40   *
  41   * @param array $attributes The block attributes.
  42   *
  43   * @return string Returns the post content with latest posts added.
  44   */
  45  function render_block_core_latest_posts( $attributes ) {
  46      global $post, $block_core_latest_posts_excerpt_length;
  47      static $rendering_stack = array();
  48  
  49      $args = array(
  50          'posts_per_page'      => $attributes['postsToShow'],
  51          'post_status'         => 'publish',
  52          'order'               => $attributes['order'],
  53          'orderby'             => $attributes['orderBy'],
  54          'ignore_sticky_posts' => true,
  55          'no_found_rows'       => true,
  56      );
  57  
  58      $block_core_latest_posts_excerpt_length = $attributes['excerptLength'];
  59      add_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );
  60  
  61      if ( ! empty( $attributes['categories'] ) ) {
  62          $args['category__in'] = array_column( $attributes['categories'], 'id' );
  63      }
  64      if ( isset( $attributes['selectedAuthor'] ) ) {
  65          $args['author'] = $attributes['selectedAuthor'];
  66      }
  67  
  68      $query = new WP_Query( $args );
  69  
  70      if ( isset( $attributes['displayFeaturedImage'] ) && $attributes['displayFeaturedImage'] ) {
  71          update_post_thumbnail_cache( $query );
  72      }
  73  
  74      $list_items_markup = '';
  75      // Snapshot the current global post so it can be restored after the loop.
  76      // We use have_posts()/the_post() rather than foreach so that setup_postdata()
  77      // is called for each post, establishing the correct global context for
  78      // do_blocks() and other filters that run during full-content rendering.
  79      $previous_post = $post ?? null;
  80  
  81      while ( $query->have_posts() ) {
  82          $query->the_post();
  83          $post_link = esc_url( get_permalink() );
  84          $title     = get_the_title();
  85  
  86          if ( ! $title ) {
  87              $title = __( '(no title)' );
  88          }
  89  
  90          $list_items_markup .= '<li>';
  91  
  92          if ( $attributes['displayFeaturedImage'] && has_post_thumbnail() ) {
  93              $image_style = '';
  94              if ( isset( $attributes['featuredImageSizeWidth'] ) ) {
  95                  $image_style .= sprintf( 'max-width:%spx;', $attributes['featuredImageSizeWidth'] );
  96              }
  97              if ( isset( $attributes['featuredImageSizeHeight'] ) ) {
  98                  $image_style .= sprintf( 'max-height:%spx;', $attributes['featuredImageSizeHeight'] );
  99              }
 100  
 101              $image_classes = 'wp-block-latest-posts__featured-image';
 102              if ( isset( $attributes['featuredImageAlign'] ) ) {
 103                  $image_classes .= ' align' . $attributes['featuredImageAlign'];
 104              }
 105  
 106              $featured_image = get_the_post_thumbnail(
 107                  null,
 108                  $attributes['featuredImageSizeSlug'],
 109                  array(
 110                      'style' => esc_attr( $image_style ),
 111                  )
 112              );
 113              if ( $attributes['addLinkToFeaturedImage'] ) {
 114                  $featured_image = sprintf(
 115                      '<a href="%1$s" aria-label="%2$s">%3$s</a>',
 116                      esc_url( $post_link ),
 117                      esc_attr( $title ),
 118                      $featured_image
 119                  );
 120              }
 121              $list_items_markup .= sprintf(
 122                  '<div class="%1$s">%2$s</div>',
 123                  esc_attr( $image_classes ),
 124                  $featured_image
 125              );
 126          }
 127  
 128          $list_items_markup .= sprintf(
 129              '<a class="wp-block-latest-posts__post-title" href="%1$s">%2$s</a>',
 130              esc_url( $post_link ),
 131              $title
 132          );
 133  
 134          if ( isset( $attributes['displayAuthor'] ) && $attributes['displayAuthor'] ) {
 135              $author_display_name = get_the_author_meta( 'display_name' );
 136  
 137              /* translators: byline. %s: author. */
 138              $byline = sprintf( __( 'by %s' ), $author_display_name );
 139  
 140              if ( ! empty( $author_display_name ) ) {
 141                  $list_items_markup .= sprintf(
 142                      '<div class="wp-block-latest-posts__post-author">%1$s</div>',
 143                      $byline
 144                  );
 145              }
 146          }
 147  
 148          if ( isset( $attributes['displayPostDate'] ) && $attributes['displayPostDate'] ) {
 149              $list_items_markup .= sprintf(
 150                  '<time datetime="%1$s" class="wp-block-latest-posts__post-date">%2$s</time>',
 151                  esc_attr( get_the_date( 'c' ) ),
 152                  get_the_date( '' )
 153              );
 154          }
 155  
 156          if ( isset( $attributes['displayPostContent'] ) && $attributes['displayPostContent']
 157              && isset( $attributes['displayPostContentRadio'] ) && 'excerpt' === $attributes['displayPostContentRadio'] ) {
 158  
 159              $trimmed_excerpt = get_the_excerpt();
 160  
 161              /*
 162               * Adds a "Read more" link with screen reader text.
 163               * [&hellip;] is the default excerpt ending from wp_trim_excerpt() in Core.
 164               */
 165              if ( str_ends_with( $trimmed_excerpt, ' [&hellip;]' ) ) {
 166                  /** This filter is documented in wp-includes/formatting.php */
 167                  $excerpt_length = (int) apply_filters( 'excerpt_length', $block_core_latest_posts_excerpt_length );
 168                  if ( $excerpt_length <= $block_core_latest_posts_excerpt_length ) {
 169                      $trimmed_excerpt  = substr( $trimmed_excerpt, 0, -11 );
 170                      $trimmed_excerpt .= sprintf(
 171                          /* translators: 1: A URL to a post, 2: Hidden accessibility text: Post title */
 172                          __( '… <a class="wp-block-latest-posts__read-more" href="%1$s" rel="noopener">Read more<span class="screen-reader-text">: %2$s</span></a>' ),
 173                          esc_url( $post_link ),
 174                          esc_html( $title )
 175                      );
 176                  }
 177              }
 178  
 179              if ( post_password_required() ) {
 180                  $trimmed_excerpt = __( 'This content is password protected.' );
 181              }
 182  
 183              $list_items_markup .= sprintf(
 184                  '<div class="wp-block-latest-posts__post-excerpt">%1$s</div>',
 185                  $trimmed_excerpt
 186              );
 187          }
 188  
 189          if ( isset( $attributes['displayPostContent'] ) && $attributes['displayPostContent']
 190              && isset( $attributes['displayPostContentRadio'] ) && 'full_post' === $attributes['displayPostContentRadio'] ) {
 191  
 192              if ( post_password_required() ) {
 193                  $post_content = __( 'This content is password protected.' );
 194              } else {
 195                  $post_id      = get_the_ID();
 196                  $post_content = get_post_field( 'post_content', $post_id, 'raw' );
 197                  // Check if we're already rendering this post to prevent infinite recursion.
 198                  if ( in_array( $post_id, $rendering_stack, true ) ) {
 199                      $post_content = '';
 200                  } else {
 201                      $rendering_stack[] = $post_id;
 202  
 203                      try {
 204                          // Run through the actions that are typically taken on the_content.
 205                          $post_content = _wp_apply_block_content_filters( $post_content, 'latest-posts' );
 206                      } finally {
 207                          array_pop( $rendering_stack );
 208                      }
 209                  }
 210              }
 211  
 212              $post_content       = str_replace( ']]>', ']]&gt;', $post_content );
 213              $list_items_markup .= sprintf(
 214                  '<div class="wp-block-latest-posts__post-full-content">%1$s</div>',
 215                  $post_content
 216              );
 217          }
 218  
 219          $list_items_markup .= "</li>\n";
 220      }
 221  
 222      // Restore the post context that was active before this secondary query.
 223      // wp_reset_postdata() is intentionally not used here: when this block is
 224      // rendered inside another post's content (e.g. via do_blocks()), it would
 225      // restore to the main query post rather than the outer rendering post.
 226      $post = $previous_post;
 227      if ( $previous_post instanceof WP_Post ) {
 228          setup_postdata( $previous_post );
 229      }
 230  
 231      remove_filter( 'excerpt_length', 'block_core_latest_posts_get_excerpt_length', 20 );
 232  
 233      $layout             = $attributes['layout'] ?? array();
 234      $legacy_layout_type = (
 235          isset( $attributes['postLayout'] ) &&
 236          'grid' === $attributes['postLayout']
 237      ) ? 'grid' : 'default';
 238      $layout_type        = $layout['type'] ?? $legacy_layout_type;
 239      $column_count       = $layout['columnCount'] ?? ( $attributes['columns'] ?? null );
 240  
 241      $classes = array( 'wp-block-latest-posts__list' );
 242      if ( 'grid' === $layout_type ) {
 243          $classes[] = 'is-grid';
 244      }
 245      if ( 'grid' === $layout_type && ! empty( $column_count ) ) {
 246          $classes[] = sanitize_title( 'columns-' . $column_count );
 247      }
 248      if ( 'grid' === $layout_type && ! empty( $column_count ) && ! empty( $layout['minimumColumnWidth'] ) ) {
 249          $classes[] = 'has-native-responsive-grid';
 250      }
 251      if ( isset( $attributes['displayPostDate'] ) && $attributes['displayPostDate'] ) {
 252          $classes[] = 'has-dates';
 253      }
 254      if ( isset( $attributes['displayAuthor'] ) && $attributes['displayAuthor'] ) {
 255          $classes[] = 'has-author';
 256      }
 257      if ( isset( $attributes['style']['elements']['link']['color']['text'] ) ) {
 258          $classes[] = 'has-link-color';
 259      }
 260  
 261      $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => implode( ' ', $classes ) ) );
 262  
 263      return sprintf(
 264          '<ul %1$s>%2$s</ul>',
 265          $wrapper_attributes,
 266          $list_items_markup
 267      );
 268  }
 269  
 270  /**
 271   * Registers the `core/latest-posts` block on server.
 272   *
 273   * @since 5.0.0
 274   */
 275  function register_block_core_latest_posts() {
 276      register_block_type_from_metadata(
 277          __DIR__ . '/latest-posts',
 278          array(
 279              'render_callback' => 'render_block_core_latest_posts',
 280          )
 281      );
 282  }
 283  add_action( 'init', 'register_block_core_latest_posts' );
 284  
 285  /**
 286   * Handles outdated versions of the `core/latest-posts` block by converting
 287   * attribute `categories` from a numeric string to an array with key `id`.
 288   *
 289   * This is done to accommodate the changes introduced in #20781 that sought to
 290   * add support for multiple categories to the block. However, given that this
 291   * block is dynamic, the usual provisions for block migration are insufficient,
 292   * as they only act when a block is loaded in the editor.
 293   *
 294   * TODO: Remove when and if the bottom client-side deprecation for this block
 295   * is removed.
 296   *
 297   * @since 5.5.0
 298   *
 299   * @param array $block A single parsed block object.
 300   *
 301   * @return array The migrated block object.
 302   */
 303  function block_core_latest_posts_migrate_categories( $block ) {
 304      if (
 305          'core/latest-posts' === $block['blockName'] &&
 306          ! empty( $block['attrs']['categories'] ) &&
 307          is_string( $block['attrs']['categories'] )
 308      ) {
 309          $block['attrs']['categories'] = array(
 310              array( 'id' => absint( $block['attrs']['categories'] ) ),
 311          );
 312      }
 313  
 314      return $block;
 315  }
 316  add_filter( 'render_block_data', 'block_core_latest_posts_migrate_categories' );


Generated : Sun Jul 19 08:20:17 2026 Cross-referenced by PHPXref