WordPress and buddypress programming

list upcoming post titles with dates using a shortcode without a plugin in WordP

Viewing 0 reply threads
  • Author
    Posts
    • #9952
      Michael Mc
      Keymaster
      @mkmcst
      
      /**
       * Shortcode to display upcoming posts with titles and dates
       *
       * @param array $atts Shortcode attributes
       * @return string
       */
      function display_upcoming_posts( $atts ) {
          $atts = shortcode_atts( array(
              'posts_per_page' => '5', // Default number of posts to display
          ), $atts, 'upcoming_posts' );
      
          $args = array(
              'post_status' => 'future', // Only future posts
              'posts_per_page' => $atts['posts_per_page'],
              'orderby' => 'date',
              'order' => 'ASC', // Order by date, ascending
          );
      
          $upcoming_posts = get_posts( $args );
      
          if ( empty( $upcoming_posts ) ) {
              return '<p>No upcoming posts found.</p>';
          }
      
          $output = '<ul class="upcoming-posts">';
          foreach ( $upcoming_posts as $post ) {
              $output .= '<li>';
              $output .= '<a href="' . esc_url( get_permalink( $post->ID ) ) . '">' . esc_html( get_the_title( $post->ID ) ) . '</a>';
              $output .= ' (' . esc_html( get_the_date( '', $post->ID ) ) . ')';
              $output .= '</li>';
          }
          $output .= '</ul>';
      
          return $output;
      }
      add_shortcode( 'upcoming_posts', 'display_upcoming_posts' );
      

      Add the shortcode: [upcoming_posts posts_per_page=”3″] (replace “3” with the desired number of posts).

Viewing 0 reply threads
  • You must be logged in to reply to this topic.