Search code examples
wordpressdatearchivecustom-fieldsdynamic-linking

Wordpress customized archive page link via custom date field


I customized a WordPress archive page which displays a list of posts filtered by a custom date field called 'email_blast_date'. I am trying to figure out how to generate a link in my header or sidebar that directs users to the archive page with the latest 'email_blast_date' day that contains published posts. I'm still a new WP developer... this is what I know:

  • I've got the archive page working, based off my custom field 'email_blast_date rather' rather than published date.

  • Archive page URL is structured and working with the "Day and name" permalink settings (domain.com/%year%/%month%/%day%/).

    • I assume I need to use something like 'get_day_link();' but I am not sure how to customize that call to filter posts via my custom date field and retrieve the latest 'email_blast_date' of all published posts. The archive widget does this already but it's based off of the published date and not my custom date field.

Any you very much in advance for your help!!


Solution

  •      <?php    
         $args = array(
            'post_type'      => 'post',
               'numberposts'    => 1,
               'meta_key'       => 'email_blast_date',
               'order'          => 'DESC',
               'orderby'       => 'meta_value'
          );
    
          $loop = new WP_Query( $args );
    
          while ( $loop->have_posts() ) : $loop->the_post(); endwhile; 
    
         $eb_date = strtotime(get_post_meta( get_the_ID(), 'email_blast_date', true )); 
    
       $year  = date('Y',$eb_date); 
       $month = date('m',$eb_date);
       $day   = date('d',$eb_date); 
       $link = $year . "/" . $month . "/" . $day . "/";
       ?>
    
       <a href="<?php echo esc_url( home_url( $link ) ); ?>